简体   繁体   English

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

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

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

Everytime I type the input, it prints out "Sorry, I did not understand your input." 每次键入输入内容时,都会打印出“抱歉,我不明白您的输入内容”。 The condition "else" doesn't work. 条件“其他”不起作用。

I don't know why. 我不知道为什么 Could anyone help me? 有人可以帮我吗? Thank you very much! 非常感谢你!

Because as written, each of your if statements are independent, the else only corresponds to your last if result == 'c' , so if they don't type 'c' , they hit your else case. 因为按照书面规定,您的每个if语句都是独立的, else仅对应于您的最后一个if result == 'c' ,因此,如果它们不键入'c' ,则会命中您的else情况。

Instead, you can use if/elif/else to try each of your cases. 相反,您可以使用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