为什么条件“else”在我的python代码中不起作用

2024-09-28 05:25:39 发布

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

这是我的密码。你知道吗

highnum=100
lownum=0
guessnum=highnum/2
print "Please think of a number between 0 and 100!"
while True:
    print "Is your secret number is "+str(guessnum)+"?"
    print "Enter 'h' to indicate the guess is too high.",
    print "Enter 'l' to indicate the guess is too low. ",
    print "Enter 'c' to indicate I guessed correctly."
    result=raw_input()
    if result=="h":
        highnum=guessnum
        guessnum=int(highnum+lownum)/2
    if result=="l":
        lownum=guessnum
        guessnum=int(highnum+lownum)/2
    if result=="c":
        break
    else:
        print "Sorry, I did not understand your input."
print "Game over. Your secret number was: "+str(guessnum)+" ."

每次我输入时,它都会打印出“对不起,我不明白你的输入。”条件“else”不起作用。你知道吗

我不知道为什么。有人能帮我吗?非常感谢你!你知道吗


Tags: thetonumberyoursecretifisresult
1条回答
网友
1楼 · 发布于 2024-09-28 05:25:39

因为在编写时,每个if语句都是独立的,else只对应于最后一个if result == 'c',所以如果它们不键入'c',它们就会命中你的else大小写。你知道吗

相反,您可以使用if/elif/else来尝试每个案例。你知道吗

if result=="h":
    highnum=guessnum
    guessnum=int(highnum+lownum)/2
elif result=="l":
    lownum=guessnum
    guessnum=int(highnum+lownum)/2
elif result=="c":
    break
else:
    print "Sorry, I did not understand your input."

相关问题 更多 >

    热门问题