Home > other >  I am trying to make a while loop that has not in it and its not working
I am trying to make a while loop that has not in it and its not working

Time:05-03

playerpoint = [2, 2]
#this works with the [5, 2] but not with the other point
while not playerpoint == [5, 2] or not playerpoint == [0, 2]:
space = input("Enter W to go up\nEnter A to go right\nEnter D to go left\nEnter S to go down ")
Move(space)
playerpoint = [5, 2]

CodePudding user response:

Think about it: of those two “or” conditions, at least one will always be true. The loop will therefore run forever. Consider whether you mean “and” and not “or”.

Another option — one that’s both more “Pythonic” and easier to read — is to explicitly aloof while the point is a member of a specific set of points (thanks @onecricketeer):

while playerpoint not in {[5, 2],  [0, 2]}:

CodePudding user response:

The thing to keep in mind here is that when you add a negation to a condition that's a disjunction (or) or a conjunction (and) means you have to flip the conjunction to a disjunction, or vice versa - known in logic as DeMorgan's laws:

This is why not a or not b is not equivalent to not(a or b) but rather to not(a and b).

To illustrate with your example: Since the variable playerpoint cannot be both [5, 2] and [0, 2] at the same time, in your condition, one of the two negated conditions will inevitably be true: If playerpoint is [0, 2], then it will meet the not [5, 2] condition, or vice versa.

Presumably, the condition you want to test is that playerpoint is neither of the two. You can test this, under DeMorgan's Laws, as playerpoint != [5,2] and playerpoint != [0,2]. The more "Pythonic" way of expressing this would, however, be not playerpoint in [[5,2], [0,2]] (which says the same but a bit more succinctly).

  • Related