Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #79009

Re: while loop - multiple condition

From Roy Smith <roy@panix.com>
Newsgroups comp.lang.python
Subject Re: while loop - multiple condition
Date 2014-10-12 13:28 -0400
Organization PANIX Public Access Internet and UNIX, NYC
Message-ID <roy-5A8BE2.13280512102014@news.panix.com> (permalink)
References <mailman.14792.1413133694.18130.python-list@python.org>

Show all headers | View raw


In article <mailman.14792.1413133694.18130.python-list@python.org>,
 Shiva <shivaji_tn@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 
once.

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

Back to comp.lang.python | Previous | Next — Previous in thread | Next in thread | Find similar | Unroll thread


Thread

while loop - multiple condition Shiva <shivaji_tn@yahoo.com> - 2014-10-12 17:08 +0000
  Re: while loop - multiple condition Roy Smith <roy@panix.com> - 2014-10-12 13:28 -0400
  Re: while loop - multiple condition Denis McMahon <denismfmcmahon@gmail.com> - 2014-10-12 19:35 +0000

csiph-web