[英]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.