Hello

I am new to Python and I have a question for a simple piece of code as below:

temp = '32'
if temp > 85:
   print "Hot"
elif temp > 62:
   print "Comfortable" 
else:
   print "Cold" 

According to my understanding, when the program compiles and goes to line 2, it checks if 32>85 and its not true so goes to next condition and checks if 32>62 and its not true and goes to else and should print "Cold"

However, I see the answer is : "Hot" . Can anyone please explain how is it "Hot" ?

It is because temp is a string (str type) while 85 is an integer. Integer comparison is different from string comparison (string ordering is lexicographic order). You should do

temp = int('32')

to convert to int for example.

This problem does not exist in recent versions of python where comparison of unordered data types is impossible. See the difference between python 2.7

>>> '32' > 85
True

and python 3.4

>>> '32' > 85
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unorderable types: str() > int()

If you have the choice, learn python with python 3.4.

Thanks a lot , it is clear now.And, thanks for the suggestion regarding 3.4 too but the course I am doing supports 2.7 only :(

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.