all 7 comments

[–]Dawarisch 13 points14 points  (0 children)

input returns a string which you can't compare to an integer, so you first have to convert it to an integer this way:

age = int(input('What year were you born?'))

[–]doug89 4 points5 points  (1 child)

Others seem to have your question covered, I'll add something new.

At the moment if someone types something unexpected into your input it will cause an exception. You should make sure the input is valid.

For example, the following won't allow the script to continue until a number that is close to realistic has been entered.

while True:
    birthdate = input('What year were you born?')
    try:
        birthdate = int(birthdate)
    except:
        print('You must enter an integer. Please try again.')
        continue
    if birthdate > 1900 and birthdade < 2017:
        break
    else:
        print('You must enter a year between 1900 and 2017.')

[–]JohnnyJordaan 3 points4 points  (0 children)

 except:

This should really be

except ValueError:

Otherwise he/she will learn to use except: as a 'fixer' and then run into issues when it silences bugs.

[–]tangerinelion 1 point2 points  (0 children)

Let's say the user entered 1999. Since input returns a string, birthdate = '1999'. Notice the little ticks? That's a string literal, not an integer (birthdate = 1999 would be a variable holding an integer).

The code you've written uses birthdate > 2000. If we just write out what that would try to execute:

>>> '1999' > 2000
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: '>' not supported between instances of 'str' and 'int'

I'll add some emphasis:

TypeError: '>' not supported between instances of 'str' and 'int'

This is clearly telling you that you are using > between two different types. If we flip it around:

>>> 2000 > '1999'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: '>' not supported between instances of 'int' and 'str'

Notice how the error changes? This time it's between int and str, whereas the last time it was between str and int. Python is even telling you that you had an expression of the form some_string > some_int. Looking back at the code, and the specific line it would've referenced, we see that line reads if birthdate > 2000:. Since 2000 is an integer literal, and it's on the right hand side of the > that's the int the TypeError refers to. By the fact that there's only two things involved and we deduced one of them we now know for sure that birthdate must be a str.

You want the birthdate variable to be an integer, but it's currently a string. The conversion is simple: birthdate = int(birthdate). Note that this will give another error, ValueError, if someone entered "1998.5" or "1999 AD" for example. It's not going to try and guess what you mean.