Python Forum

Full Version: TypeError: can't multiply sequence by non-int of type 'str'
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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.
The input function returns a string, so you need to convert those values to numeric ones, using the int or float functions as appropriate.
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)))