第二个If语句没有按预期工作

时间:2017-08-29 19:58:57

标签: python python-3.x

我的儿子写了一个代码,这很简单,但第二个if语句没有按预期工作。

print ('hi')
print ('How are you?')
print ('Hope ok!')
print ('So I will ask you a few questions')
print ('What is 2 + 2?')
answer = input() 
if answer == 4:
    print ('Well done!')
else:
    print ('Are you able to count?')
    print ('Well anyway.Another question.')
    print ('What is 50 % 50?')

anser = input() 

if anser == 1:
    print ('Well done!')
elif anser == 5:
    print ('What?')
elif anser == 50:
    print ('Who are you? Are you already in 1st class?')
else:
    print ('Ok.I got you.You cannot count.')
    print ('Арролбьітрцо')
    print ('The code is broken! can you fix it?')
    print ('Press Enter')
    input()
    for i in range (1,70):
        print ('Error')

第二个答案无关紧要,程序仍然打印

“好的。我找到了你。你不能算数。 Арролбьітрцо 代码坏了!你能修好它吗? 按Enter“

即使您输入1或5 ......

任何人都可以建议那些错误。

谢谢。

3 个答案:

答案 0 :(得分:1)

原因是因为anser是str。如果您在print(type(anser))之后放置anser = input(),则会看到

  

<class 'str'>

if anser == 1:更改为if anser == '1':然后就可以了

答案 1 :(得分:0)

除非另有指定,否则使用input()将始终生成字符串。

要使其成为整数:

answer = int(input("question"))

另一种选择是:

if int(answer) == 1:

这将使它成为一个整数,因此您要比较if语句中的两个数字

答案 2 :(得分:-1)

基本上,当您使用一个或多个对象使用==运算符进行比较时,Python将检查指针是否相同(实质上,如果它们位于内存中的相同位置)。您有两种类型的数据,基元(如整数或布尔值)和对象。使用==运算符时,字符串不会与pimitives进行比较,因此您必须将数字转换为字符串或将输入转换为int

而不是:如果anser == 5:

执行:if int(anser)== 5:

或者:如果anser ==&#39; 5&#39;