user2775042
user2775042

Reputation: 509

How do I fix this python loop?

outcome=input("higher or lower")

while (outcome!= 'h' or outcome!= 'l'): 
    outcome=input("enter h or l")

print("its working")

the while loop keeps going even when i write H or L

Upvotes: 0

Views: 72

Answers (1)

paxdiablo
paxdiablo

Reputation: 881113

You need and rather than or.

Let's assume the lowercase/uppercase issue is not a problem and you enter h rather than H.

Your expression will then be:

'h' != 'h' or 'h' != 'l'
\________/    \________/
   false   or    true
   \________________/
         true

Since an object cannot be two things at once, one of those inequalities must be true. Hence the entire expression must be true.

Hence you should change it to something like:

while (outcome != 'h') and (outcome != 'l'):

or:

while outcome not in ('h', 'l'):

the latter being more succinct as the number of possibilities increases:

while outcome not in ('n', 's', 'e', 'w', 'u', 'd', 'l', 'r'):

Upvotes: 6

Related Questions