runners3431
runners3431

Reputation: 1455

Why does my string comparison fail on the first test?

If I enter, h or l, c It keeps prompting me to enter a number instead of going to the correct case.

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 

Upvotes: 0

Views: 77

Answers (1)

Bhargav Rao
Bhargav Rao

Reputation: 52161

Your condn exp is wrong, it should be

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

This means that if the value is not h and l and c then execute. Your statement instead implied that if the input is not h or l or c then execute. So when you give h as input it fails as it is not l and c

Or as mentioned in a comment, you can instead do,

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

Upvotes: 3

Related Questions