if语句总是给出相同的答案python初学者

时间:2016-12-08 21:03:07

标签: python if-statement

python总是回答你很可能有资格工作,即使我输入的数字低于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")

2 个答案:

答案 0 :(得分:0)

您正在比较字符串(question2)和整数(18)。与PHP之类的其他语言相反,字符串不会事先自动转换为int,并且int也不会转换为字符串。

在这样的比较中,int 总是&lt;一个字符串。您必须将int(question2)与18进行比较。

有关完整说明,请参阅here

答案 1 :(得分:0)

那是因为原始输入要求未定义的字符串而不是整数 当python接收它接收的输出时

question2 = "16"

而不是

question2 = 16

以下是对您的代码的修复:

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")

因为现在python将字符串转换为整数

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

我建议使用python 3(这是我的观点)它使这更简单

-Joshua

相关问题