为什么我的字符串比较在第一次测试时失败?

时间:2015-01-21 18:30:40

标签: python

如果我输入,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 

1 个答案:

答案 0 :(得分:3)

你的condn exp错了,应该是

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

这意味着,如果该值不是h,而lc则执行。您的声明反而暗示,如果输入不是hlc,则执行。因此,当您将h作为输入时,它会失败,因为它不是lc

或者如comment中所述,您可以改为

if guess not in ['h', 'l', 'c']:
相关问题