简体   繁体   中英

if statement always giving same answer python beginner

python always answers you are likely to be eligible for work even though I typed a number under 18

question1= raw_input("are you fat?")
if question1== ("yes"):
    print ("sorry you are not fit for work")
elif question1== ("no"):
    print ("you may be eligible for work, move on to the next question please")
    question2= raw_input("how old are you?")
    if question2 >= 18:
        print ("you are likely to be eligible for work")
    elif question2 < 18:
        print ("sorry come back when you're older")

You are comparing a string ( question2 ) and an integer ( 18 ). Contrary to other languages like PHP, the string is not automatically converted to an int beforehand, and the int is not converted to a string either.

In such a comparison, an int is always < a string. You must compare int(question2) with 18.

See here for the full explanation.

That would be because raw input is asking for a undefined string of characters not an integer when python takes in the output it receives

question2 = "16"

Rather than

question2 = 16

Here would be a fix to your code:

question1= raw_input("are you fat?")
if question1== ("yes"):
    print ("sorry you are not fit for work")
elif question1== ("no"):
    print ("you may be eligible for work, move on to the next question please")
    question2= int(raw_input("how old are you?"))
        if question2 >= 18:
            print ("you are likely to be eligible for work")
        elif question2 < 18:
            print ("sorry come back when you're older")

Because now python converts the string into an integer

question2= int(raw_input("how old are you?"))

I would recommend using python 3 though (This is my opinion) It makes this simpler

-Joshua

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM