Chris434
Chris434

Reputation: 21

My code starts yielding illogical answers when a I deal with number bigger than 99

I am trying to write a program that determines a person stage of life, whether the person is a baby, kid, teenager, adult or elder. The program starts with a variable that contains an input() function that allows the user to type in an age so the program can start running.

The issue is that when I type ages higher than 99, the program prompts that the person whose age has been typed in is a baby. So basically, according to the program someone who is 123 years old is a baby, which does not make sense.

age=input("enter the person's age: ")

if age<'2':
    print('the person is a baby')

elif age=='2' and age<'4':
    print('the person is a toddler')

elif age >='4' and age<'13':
    print ('the person is a kid')

elif age>='13' and age<'20':
    print('the person is a teenager')

elif age>='20' and age<'65':
    print('the person is an adult')

elif age>='65':
    print('the person is an elder')

I am wondering if I am making a mistake on my code, although it seems to me pretty straight forward. Anyways, I am guessing there is some theoretical knowledge that I am missing, if that is the case I would appreciate if you folks can shed some light on the whole issue.

Upvotes: 1

Views: 49

Answers (3)

Subhash
Subhash

Reputation: 3260

You should convert age to an integer and then compare. You are comparing strings, and that gives you weird answers.

Reformatted code:

age_str=input("enter the person's age: ")

try:
    age = int(age_str)
except:
    print("Invalid Entry. Enter age as a number.")
    exit(0)

if age < 2:
    print('the person is a baby')
elif age == 2 and age < 4:
    print('the person is a toddler')
elif age >= 4 and age < 13:
    print('the person is a kid')
elif age >= 13 and age < 20:
    print('the person is a teenage r')
elif age >= 20 and age < 65:
    print('the person is an adult')
elif age >= 65:
    print('the person is an elder')

Code also checks for invalid entries above. If anything other than an integer is entered, it throws an error.

Upvotes: 1

c0rp3n
c0rp3n

Reputation: 91

You are comparing strings no integers thus '100' is less than '99' as the first and second characters are less. You need to convert your input to an integer and thenuuse that for the comparisons and then you shall be fine.

Upvotes: 1

Adrian
Adrian

Reputation: 177

What you are essentially doing here is comparing strings which does not translate to the behavior you are seeking. You will need to cast the input as int() first.

If you know the input is guaranteed to be formatted correctly, use:

age = int(input("enter the person's age: "))

However, nobody is perfect so it would be best to wrap in a try-except:

age = input("enter the person's age: ")
try:
    age = int(age)
except:
    # Handle exception

if age < 2:
    # Do something
elif ...
    # Do more stuff

Upvotes: 3

Related Questions