Shiney
Shiney

Reputation: 81

Always true conditions

I have the following Python script:

playerInput = ""
x = playerInput != "a";
y = playerInput != "b";
while x or y:
    playerInput = input();

The problem is both conditions are always true, no matter, what I write.

Upvotes: 0

Views: 96

Answers (2)

Lucas Wieloch
Lucas Wieloch

Reputation: 818

Try this:

playerInput = ""
while (playerInput != "a") and (playerInput != "b"):
    playerInput = input()

The main problem is you assign x and y before the loop.

Upvotes: 2

Prune
Prune

Reputation: 77900

Both conditions are True because you set them that way before the loop (ostensibly you gave playerInput some initial value other than a or b), and you never change their values. Get rid of those one-letter names; they don't help make your code clear. Also, work through a tutorial on Boolean operations: you've made a common mental slip in your compound condition: you will have a hard time finding a value that will make both conditions False.

playerInput = input()
while (playerInput != "a") and \
      (playerInput != "b"):
    playerInput = input()

Perhaps more "Pythonic" is

while not playerInput in ("a", "b"):
    playerInput = input("Please choose 'a' or 'b': ")

Upvotes: 3

Related Questions