Python Forum
TypeError: can't multiply sequence by non-int of type 'str' - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: TypeError: can't multiply sequence by non-int of type 'str' (/thread-24188.html)



TypeError: can't multiply sequence by non-int of type 'str' - emmapaw24 - Feb-03-2020

Hi, I'm new to python so the answer to this may be obvious, but I'm trying to write code to find the cost of electricity used by a device using wattage, the number of hours used, and electricity cost. The code I've written is:

wattage = input("What is the wattage of your device?")
hoursUsed = input("What is the amount of hours used?")
pricePerKWh = 11.76
electricityCost = ((wattage * hoursUsed)/(1000 * pricePerKWh))
print("The cost of electricity is:" + str(electricityCost))

When I run this is recieve:

What is the wattage of your device?3
What is the amount of hours used?3
Traceback (most recent call last):
File "C:/Users/Windows/Documents/lab3.py", line 4, in <module>
electricityCost = ((wattage * hoursUsed)/(1000 * pricePerKWh))
TypeError: can't multiply sequence by non-int of type 'str'
>>>

I can't figure out what I'm doing wrong in the code, again this might be obvious but I'm new to this, thanks in advance.


RE: TypeError: can't multiply sequence by non-int of type 'str' - ndc85430 - Feb-03-2020

The input function returns a string, so you need to convert those values to numeric ones, using the int or float functions as appropriate.


RE: TypeError: can't multiply sequence by non-int of type 'str' - michael1789 - Feb-03-2020

There are different "types" of information in python. "int" refers to "integer", and "str" refers to "string". You inputs collect a "string", which is just a series of characters, could be letters or numbers and has no mathematical value. If you want to do math with a string you need to convert it to a number-type variable first.

#here is one way
electricityCost = ((wattage * int(hoursUsed))/(1000 * int(pricePerKWh)))