[Tutor] While loop issue, variable not equal to var or var

Peter Otten __peter__ at web.de
Sat Jul 12 09:10:25 CEST 2014

Steve Rodriguez wrote:

> Hey guys n gals,
> New to python, having some problems with while loops, I would like to make
> a program quick once q or Q is typed, but thus far I can only get the
> first variable to be recognized. My code looks like:
>     message = raw_input("-> ")
>     while message != 'q':
>         s.send(message)
>         data = s.recv(2048)
>         print str(data)
>         message = raw_input("-> ")
>     s.close()
>     print("Shutting Down")
> I've tried:
> while message != 'q' or 'Q':

This evaluates 

(message != "q") or "Q"

and "Q" is always True in a boolean context:

>>> bool("Q")

> while message != 'q' or message != 'Q':

This is true when at least one of the subexpressions

message != "q"
message != "Q"

is True. When the value of message is "q" it must be unequal to "Q" and vice 
versa, so there is always at least one true subexpression.

> while message != ('q' or 'Q'):

When you try the right side in the interactive interpreter you get

>>> "q" or "Q"

so this is the same as just 

message != "q" 

> Any ideas would be much appreciated! Thanks! :D

while message.lower() != "q":
while message not in ("q", "Q"):
while message != "q" and message != "Q":

There's another one that chains boolean expressions

while "q" != message != "Q":

that I don't recommend here but that is very readable for checking number 

if 0 <= some_number < 1:
   print some_number, "is in the half-open interval [0,1)"

You also may consider an infinite loop:

while True:
    message = raw_input("-> ")
    if message in ("q", "Q"):

This avoids the duplicate raw_input().

PS: You sometimes see

message in "qQ"

but this is buggy as it is true when the message is either
"q", "Q", or "qQ".

More information about the Tutor mailing list