This program is supposed to calculate the number of degrees below 60 on a given day then create a running sum of degrees. count equals the sum of degrees below 60. However, when I run it I get this error:
cool = 60 - temp
TypeError: unsupported operand type(s) for -: 'int' and 'str'
Any ideas on why it's doing this? Thanks!
def cold_days():
temp = eval(input("What is the temperature? "))
count = 0
if temp < 60:
while temp !="quit":
temp = eval(input("What is the temperature? "))
cool = 60 - temp
count = count + heat
print(count)
else:
print("you have no cold days")
4 Answers 4
You need to turn temp into an int:
...
try:
temp = int(temp)
except TypeError:
# Handle invalid integer
print("%s is not a valid integer." % temp)
sys.exit(1)
...
Comments
In Python 3, the input() function always returns a string (this is different from Python 2, and could be the source of the confusion since the Python tutorial you're using might be unaware of Python 3). Since Python is strongly (but dynamically) typed, you can't perform arithmetic calculations using a string and an integer, as your error message shows. You must first convert the temp string into an integer using int():
temp = int(temp)
If temp does not contain something that can be converted to an integer, you will get a ValueError exception. By default, an exception will terminate your program with an informative error message. To handle the exception and take alternative action, your Python tutorial should have a whole chapter on that.
Comments
You can just drop the 'eval' since input does return the correct type. Or typecast the temp to int:
temp = int(temp)
1 Comment
input() always returns a string (this was different in Python 2, which used raw_input()) to do the same thing.I think you need to rethink how you are reading in data. input() returns eval() of whatever text the user types in, so I would expect an error when the user types "quit".
Instead, I suggest using raw_input() which returns text. Then check if it is equal to "quit" before converting to an int.
2 Comments
input() always returns a string, and raw_input() does not exist.
eval(input(...))? What else have you tried to get user input? And, which version Python are you using (2 or 3)?