#🔒 Why is this loop not exiting when it gets the correct value to exit?

26 messages · Page 1 of 1 (latest)

low haven
#

Hi. Here is my code. This loop is supposed to exit out when it gets the correct input from the user, but it keeps on getting an infinite loop even with the correct input.

print("Enter a direction. W is up S is down A is left and D is right.")
direction_input = input().upper()
while(direction_input != 'W' or direction_input != 'A' or direction_input != 'S' or direction_input != 'D'):
    print("Enter a direction. W is up S is down A is left and R is right.")
    direction_input = input().upper()

Any help would be appreciated.

rugged yarrowBOT
#

@low haven

Python help channel opened

Remember to:

  • Ask your Python question, not if you can ask or if there's an expert who can help.
  • Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
  • Explain what you expect to happen and what actually happens.

:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.

merry pecan
#

another more readable way to do this is direction_input not in [*'WASD']

oak iris
#

direction_input != 'W' or direction_input != 'A' or direction_input != 'S' or direction_input != 'D'
think about this condition. will it ever become false?

#

try carefully evaluating it for any given value of direction_input

oak iris
merry pecan
#

'WA' 'WAS' 'SD' etc

oak iris
#

ah

low haven
#

how does it work

merry pecan
#

* is often called the splat operator, it will unpack iterables into separate arguments

#

so [*'cat] gets unpacked into ['c','a','t']

#

in will check membership 'a' in ['c','a','t'] is True

#

not in just flips the result of that 'a' not in ['c','a','t'] is False

potent skiff
#

But whatever input we give the control is entering into the while condition and going to second print statement, why is that

oak iris
potent skiff
#
while(direction_input != 'W' or direction_input != 'A' or direction_input != 'S' or direction_input != 'D'```

In the above if one of the conditions is True the control should go to next line is it?
#

and if user gives input as 'Y' it will become True right

oak iris
merry pecan
#

that's the problem with the condition

potent skiff
#

So it has become never ending loop because of incorrect operator here. Understood!

rugged yarrowBOT
#
Python help channel closed

This help channel has been closed and it's no longer possible to send messages here. If your question wasn't answered, feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.