1

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")
2
  • Can you explain why you're using eval(input(...))? What else have you tried to get user input? And, which version Python are you using (2 or 3)? Commented Feb 28, 2011 at 19:18
  • I'm using 3 and I'm using eval(input... because I want the inputting value to be recognized as a python number not a string Commented Feb 28, 2011 at 19:21

4 Answers 4

3

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)

...
Sign up to request clarification or add additional context in comments.

Comments

3

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

0

You can just drop the 'eval' since input does return the correct type. Or typecast the temp to int:

temp = int(temp)

1 Comment

In Python 3, input() always returns a string (this was different in Python 2, which used raw_input()) to do the same thing.
0

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

This answer would be correct for Python 2, but not for Python 3. In Python 3, input() always returns a string, and raw_input() does not exist.
@Greg Thanks for pointing that out. I really need to get into Python 3.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.