Search code examples
pythoncanopy

missbehaviour of "OR" in python


Hy... I'm just learning python. And I have made a program like this :

guess = raw_input("please input something...");
while (guess != 'h'):
    guess = raw_input("pleae input something again....");
    print(guess);

print("Thanks...");

Well... Above program is running well. But when I put "OR" after guess != 'h' like this :

guess = raw_input("please input something...");
while (guess != 'h') or (guess != 't'):
    guess = raw_input("pleae input something again....");
    print(guess);

print("Thanks...");

Above program is running forever in while loop. What's happening there ? I thought the loop will be ended after I input either h or t


Solution

  • Your condition always holds:

    (guess != 'h') or (guess != 't')
    

    Is always true (if one part is not true it implies the other one is).

    If you use De-Morgan's law here you get something a bit more obvious:

    not (guess == 'n' and guess == 't')
    

    This is obviously always true (guess can only be one thing).

    You probably want:

    (guess != 'h') and (guess != 't')
    

    Or better yet:

    while guess not in 'ht':