'Python while string comparison
I was trying to debug some Python code of mine and I can't seem to figure this out. Any ideas why this keeps repeating if I input the correct argument for the direction input variable?
direction = input("Type 'encode' to encrypt, type 'decode' to decrypt:\n")
while direction != "encode" or direction != "encrypt" or direction != "decrypt" or direction != "decode":
print("Please put in a valid direction!\n")
direction = input("Type 'encode' to encrypt, type 'decode' to decrypt:\n")
Solution 1:[1]
Try and instead of or. Alternatively, you might find the following more readable:
while direction not in ('encode', 'encrypt', 'decrypt', 'decode'):
Solution 2:[2]
Try this:
direction = input("Type 'encode' to encrypt, type 'decode' to decrypt:\n")
method = ["encode", "encrypt", "decrypt", "decode"]
while direction not in method:
print("Please put in a valid direction!\n")
direction = input("Type 'encode' to encrypt, type 'decode' to decrypt:\n")
Solution 3:[3]
Your condition for while loop is not correct.
for example when you enter "decode" as input your encode != true is correct so loops continue
You can use this code:
direction = input("Type 'encode' to encrypt, type 'decode' to decrypt:\n")
while direction not in {"encode", "encrypt", "decode", "decrypt"} :
print("Please put in a valid direction:!")
direction = input("Type 'encode' to encrypt, type 'decode' to decrypt:\n")
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | j1-lee |
| Solution 2 | Avinash |
| Solution 3 |
