-1
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' ?

kindall
  • 178,883
  • 35
  • 278
  • 309
John Constantine
  • 1,038
  • 4
  • 15
  • 43

5 Answers5

6

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

Sterling Archer
  • 22,070
  • 18
  • 81
  • 118
4

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.

Community
  • 1
  • 1
miradulo
  • 28,857
  • 6
  • 80
  • 93
  • `'str' > 'int'` is just a coincidence here. Python explicitly puts numbers before other types, that has no connection to the alphabetical sorting order of their type names. – Martijn Pieters Mar 23 '15 at 17:18
2

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.

Community
  • 1
  • 1
Rakesh Guha
  • 366
  • 2
  • 10
0

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.

Community
  • 1
  • 1
Malik Brahimi
  • 16,341
  • 7
  • 39
  • 70
0

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.

Dean Meehan
  • 2,511
  • 22
  • 36