while loop - multiple condition

Roy Smith roy at panix.com
Sun Oct 12 19:28:35 CEST 2014

In article <mailman.14792.1413133694.18130.python-list at python.org>,
 Shiva <shivaji_tn at yahoo.com> wrote:

> Why is the second part of while condition not being checked?
> while ans.lower() != 'yes' or ans.lower()[0] != 'y':
>      ans = input('Do you like python?')
> My intention is if either of the conditions are true the loop should break.
> But the condition after 'or' doesn't seem to evaluate.

A general rule of programming (be it Python or any other language) is to 
break up complicated code into smaller pieces which can be understood 
and tested in isolation.  Your 'while' condition is kind of hairy.  
There's a couple of complicated expressions, a logical conjuction, and 
two different negated comparisons.  That's a lot to understand all at 

I would factor that out into a little function:

def is_yes(answer):
  if answer.lower() == 'yes':
    return True
  if answer.lower()[0] == 'y':
    return True
  return False

while is_yes(ans):
  ans = input('Do you like python?')

Now, you can play around with your is_yes() function in an interactive 
session and see what it returns for various inputs, in isolation from 
the rest of your program:

print is_yes('y')
print is_yes('yes')
print is_yes('no')
print is_yes('you bet your sweet bippy')

More information about the Python-list mailing list