-5

i am new to programming. According to my book, this code should get an error.

>>> age = input("How old are you? ")
How old are you? 21 
>>> age >= 18
   Traceback (most recent call last):
     File "<stdin>", line 1, in <module>
vTypeError: unorderable types: str() >= int()

In Sublime i saved a .py file:This is my .py file.

Then , in the terminal when i tried running it. It did not give me an error. First time , i ran it by entering the age 21 without the quots , it returned True. Then , i entered 17 , it returned False.

Firstly , How does my computer know that they are integers? I did not enter age=int(age).

Secondly when i input "21", its returning True. No error. Why is that happening?

How is it comparing a string and an integer?
and when i input "17" as my age, it returned True again . **Why is that happening?

It is not only comparing a sting and an integer but giving the wrong answer also this time.**

This is the screenshot of my terminal window

This is the respective terminal window after i installed python 3 This is my new .py file after installing python 3.

1 Answers1

2

You are using Python 2 and the book author is using Python 3.

In Python 2 input tries to evaluate the entered value, so the string '21' actually becomes 21 as an int.

As @Siddharth pointed out in the comments, str > int will always evaluate to True in Python 2. In Python 3 it will raise the error that is mentioned in the book.

DeepSpace
  • 78,697
  • 11
  • 109
  • 154
  • In python 2 the interpreter does not throw an error in case of a string to int comparison instead always consider string to have a higher value than int. – Siddharth Gupta Jul 22 '16 at 09:51
  • @DeepSpace i entered raw_input instead of input. and saved the file. It is still not giving any error when i enter 21 :/ in the terminal. – Rishabh Chopra Jul 22 '16 at 09:58
  • @RishabhChopra As Siddharth pointed out, `str > int` will always evaluate to `True` in Python 2. In Python 3 it will raise the error that is mentioned in the book. – DeepSpace Jul 22 '16 at 10:00
  • @RishabhChopra, if the book is using python3 I would recommend you do the same – Padraic Cunningham Jul 22 '16 at 10:00
  • Everybody, thanks for the help . I will install python 3 and get back to you. – Rishabh Chopra Jul 22 '16 at 10:08
  • As advised i installed python 3. But there is still no change. I see no error. I see exactly the same behaviour as to what i saw with python2. Please help me with this. – Rishabh Chopra Jul 22 '16 at 11:11
  • @RishabhChopra Seems like the code is still being run by the Python 2 interperter. Verify that by adding `import sys; print(sys.version_info)`. – DeepSpace Jul 22 '16 at 12:05
  • @DeepSpace In sublime , when i entered import sys; print(sys.version_info) in an empty .py file: It returned : sys.version_info(major=3, minor=5, micro=2, releaselevel='final', serial=0) – Rishabh Chopra Jul 22 '16 at 12:24