簡體   English   中英

為什么我的字符串比較在第一次測試中失敗?

[英]Why does my string comparison fail on the first test?

如果我輸入h或l,c它會不斷提示我輸入數字,而不是輸入正確的大小寫。

print("Please think of a number between 0 and 100! "); 

low = 0;
high = 100
mid = 50

while True:
    print("Is your secret number " + str(mid) + "?")
    guess = raw_input("Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low. Enter 'c' to indicate I guessed correctly.")

    if (guess != "h") or (guess != "l") or (guess != "c"):
         print "Sorry, I did not understand your input."   
         print "Is your secret number %i?" % mid
         guess = raw_input("Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low. Enter 'c' to indicate I guessed correctly.")
    elif  guess == 'l':
         low = mid
    elif  guess == 'h':
         high = mid
    else:
         print "Game over. Your secret number was: %c" % mid 
         break          
    mid = (high + low) / 2 

您的condn exp錯誤,應該是

if (guess != "h") and (guess != "l") and (guess != "c"):

這意味着如果該值不是hlc則執行。 您的陳述反而暗示如果輸入不是hlc則執行。 因此,當您將h作為輸入時,它會失敗,因為它不是lc

或者,如評論中所述 ,您可以改為,

if guess not in ['h', 'l', 'c']:

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM