0

starting to learn coding. I want my program to ask the user their age and then classify them, I understand that input() always receives a string value, so I have to convert it. I thought I could do it just once at the beginning, like this:

print ('Enter your age:')
age = input ()
int(age)

and then just compare the age value with other int values:

if age <18:
        print ('Underage')
    elif age >= 18 and age <30:
        print ('young')

But I keep getting this error: TypeError: '<' not supported between instances of 'str' and 'int'

It is fixed by doing this:

print ('Enter your age:')
age = input ()

if int(age) <18:
    print ('Underage')
elif int(age) >= 18 and int(age) <30:
    print ('young')

But I wanted to know if there is a way not to repeat the same over and over.

Thank you :)

Carcigenicate
  • 43,494
  • 9
  • 68
  • 117
meg55
  • 1
  • 1

2 Answers2

0

cast to int when you assign the variable

print ('Enter your age:')
# here
age = int(input ())

if age <18:
    print ('Underage')
elif age >= 18 and int(age) <30:
    print ('young')
Dash Winterson
  • 1,197
  • 8
  • 19
0

Two minor improvements you might make here are to just cast the string age input to an integer once. Also, the if-else logic can be streamlined:

print ('Enter your age:')
inp = input()
age = int(inp)

if age < 18:
    print ('Underage')
elif age < 30:     # age must be >= 18 already
    print ('young')
else:
    print('old')

Note that you don't need a range check here, because should the if condition fail, it means the age must be greater than 18 already.

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360