0

I am creating a simple Python program that asks for basic info about the user.

myAge= input() 
if myAge > 20:     
   print ('You must be old enough to party legally now.') 
else:     
   print ('Put that drink down!')  

MY ERROR

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

Kara
  • 6,115
  • 16
  • 50
  • 57

2 Answers2

1

The input() function returns a string as the value and you can't compare a string and an integer, in order to do that you need to perform something like the following in the if:

 myAge= input() 
if int(myAge) > 20:     
  print ('You must be old enough to party legally now.') 
else:     
  print ('Put that drink down!')
Gustavo Gomes
  • 317
  • 5
  • 13
  • That will raise `ValueError` for anything a user inputs that cannot be casted to `int`... – zwer Feb 17 '17 at 17:43
  • yes @zwer, but I assume that this is just for some simple use, of course we could put that in a try block but it seems a simplistic example though. – Gustavo Gomes Feb 17 '17 at 17:46
0

As myAge has to be an integer, it's better to convert it as soon as the user enters it:

myAge= int(input())
...
if myAge > 20:
...

and so, to fail immediately if (s)he didn't enter a valid age.

You can also catch the error and ask again:

while True:
    try:
        myAge= int(input("Please enter your age: "))
        break
    except ValueError:
        print("Your age must be an integer")

if myAge > 20:     
  print ('You must be old enough to party legally now.') 
else:     
  print ('Put that drink down!')
Thierry Lathuille
  • 23,663
  • 10
  • 44
  • 50
  • Very cool addition, thanks! Now how do i look up what functions i can use and how they work. for example to look up what try: means or what break means etc.. – SplendidMallard Feb 18 '17 at 17:40
  • The Python tutorial is a useful reference - https://docs.python.org/3.6/tutorial/errors.html (and explain the very same example, in fact...). And you can still google whatever you need, you'll find lots of answers! – Thierry Lathuille Feb 18 '17 at 17:50