Home > OS >  Python while string comparison
Python while string comparison

Time:05-11

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")

CodePudding user response:

Try and instead of or. Alternatively, you might find the following more readable:

while direction not in ('encode', 'encrypt', 'decrypt', 'decode'):

CodePudding user response:

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")

CodePudding user response:

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")
  • Related