第二个If语句未按预期工作

2024-05-29 08:15:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我儿子写了一个代码,很简单,但如果语句没有按预期工作,那就第二个。你知道吗

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

不管第二个答案是什么,程序还是打印出来的

“好吧,我明白了你。你无法计数。 Арролбьітрцо 密码坏了!你能修好它吗? 按“回车”

即使你输入1或5。。。你知道吗

有谁能告诉我出了什么事吗。你知道吗

谢谢你。你知道吗


Tags: answeryouinputifiscountwhatelse
3条回答

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

而不是:如果anser==5:

Do:如果int(anser)==5:

或者:如果anser=='5'

原因是因为anser是一个str。如果你把print(type(anser))放在anser = input()之后,你会看到

<class 'str'>

if anser == 1:改成if anser == '1':就行了

除非另行指定,否则使用input()将始终生成字符串。你知道吗

要使其成为整数,请使用:

answer = int(input("question"))

另一种选择是:

if int(answer) == 1:

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

相关问题 更多 >

    热门问题