temp = '32'
if temp > 85:
print "Hot"
elif temp > 62:
print "Comfortable"
else:
print "Cold"
Why does it give output 'Hot' , shouldn't it be 'Cold' ?
temp = '32'
if temp > 85:
print "Hot"
elif temp > 62:
print "Comfortable"
else:
print "Cold"
Why does it give output 'Hot' , shouldn't it be 'Cold' ?
Because temp
is a string and not an integer.
For Benji: we know it's a string because the value assigned to the variable is wrapped in single quotes!
More for Benji: we know it's not an integer because if it was, it would be quote-less! temp = 34
like so
As others have said, you are comparing a string to an integer, and should really just compare integers to one another. The reason why it returns True
however, is because :
>>> type('32')
<type 'str'>
>>> type(85)
<type 'int'>
>>> 'str' > 'int
True
If you were curious how different types are evaluated in Python 2.7 with <
:
>>> """any number type""" < dict() < list() < set() < str() < tuple()
True
Note that as mentioned by Martijn Pieters in the comments, number types are placed explicitly before all other types, and this behavior is not a result of the alphabetical sorting of type names.
By putting quotes around '32', you're defining it as a string, and then comparing it to an int.
Python evaluates strings to be 'greater than' ints, based on the type name: How does Python compare string and int?
Just remove the quotes around '32', and it'll work.
You are comparing a string to an integer. Strings are always greater than integers regardless of their content. See here for more on why this is the case. Just make your variable an integer.
Remove the single quotations around the number temp I.e.
temp = 42
Not
temp = '42'
This is due to letters and number strings are coverted to their ASCII equivalent then compared. An example of this is the letter 'A' = 0, 'a' = 30. You can look these values up online for more understanding.