Ad

How To Fix A While Loop That Repeats Forever, Even If The Conditions Are No Longer Met?

- 1 answer

I am creating a text-based game using python as part of a school assessment. I need to use a while loop that repeats until a variable equals 'west' or 'east'.

I have tried two methods and neither of them have worked.

These are the two methods I've used.

1:

chamber = input("Enter 'east' or 'west' to choose a chamber: ")
while 'west' not in chamber.lower() or 'east' not in chamber.lower():
    chamber = input("Enter 'east' or 'west' to choose a chamber: ")

2:

chamber = input("Enter 'east' or 'west' to choose a chamber: ")
while chamber.lower() != 'west' or 'east':
    chamber = input("Enter 'east' or 'west' to choose a chamber: ")

I expected it to loop until the variable 'chamber' is equal to either 'west' or 'east', but it keeps looping, regardless of what is entered.

Ad

Answer

first snippet does not work because always one of the sub-conditions would be True and using or the whole condition is evaluated True

the second snippet is equivalent to while chamber.lower() != 'west' or True, so again the condition will always be evaluated True

use while chamber.lower() not in ('west', 'east'):

or:

while True:
    chamber = input("Enter 'east' or 'west' to choose a chamber: ")
    if chamber.lower() in ('west', 'east'):
        break

Note you can use set {'west', 'east'}, instead of tuple ('west', 'east') which may bring performance if large number of elements. With just 2 elements there is no practical difference.

Ad
source: stackoverflow.com
Ad