While loop condition

Question:

This is a really basic question, and I apologize for its simplicity, but I have been searching for the answer and trying different syntax for hours without luck.

I am using python to create a text menu for a cipher program. I am using a while loop for an error message when an invalid key is pressed, but it loops even when the condition is false.

purpose = input("Type 'C' for coding and 'D' for decoding: ")

while purpose.upper() != "D" or "C":
    purpose = input("Error, please type a 'C' or a 'D': ")

if (purpose.upper() == "C"):
    do_something()

if (purpose.upper() == "D"):
    do_something()

For some reason the error message is displayed regardless of key press.
Thank you so much for the help!

Asked By: bdawg425

||

Answers:

Change:

while purpose.upper() != "D" or "C":

to:

while purpose.upper() != "D" and purpose.upper() != "C":

As Saish suggested in the comments below, a more pythonic way of doing that would be:

while purpose.upper() not in ("C", "D"):
Answered By: Nir Alfasi

You need to think of conditions on either side of or and and as logically independent.

When the computer sees:

while purpose.upper() != "D" or "C":

It reads it as

(purpose.upper() != "D")

OR

"C"

The second part, "C" alone, is always true.


You probably wanted:

while purpose.upper() != "D" or purpose.upper() != "C":

or better yet:

while purpose.upper() not in ("C", "D"):
Answered By: sapi

Here, try this one. it seems to work

 reason = ['D', 'C']
 while True:
     purpose = input("Type 'C' for coding and 'D' for decoding: ").upper()
     if reason.__contains__(purpose):
         print("You've got it this time")
         break

Let me know how it works out

Answered By: Zuko
while purpose.upper() != "D" or "C":

The above line will be evaluated to :

while (purpose.upper() != "D") or "C":

Expressions are evaluated left to right. Here “C” is always true, hence the loop is always executed.

You need to have something like this:

while purpose.upper() != "D" or purpose.upper() != "C":

or

#You can put it all into a list ["C", "D"] and then check 
while purpose.upper() not in ["C", "D"]:

or

#You can put it all into a tuple ("C", "D") and then check 
while purpose.upper() not in ("C", "D"):
Answered By: doubleo
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.