繁体   English   中英

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

[英]Why condition “else” doesn't work in my python code

这是我的代码。

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

每次键入输入内容时,都会打印出“抱歉,我不明白您的输入内容”。 条件“其他”不起作用。

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

因为按照书面规定,您的每个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."

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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