[Tutor] Engarde program was: i++
Danny Yoo
dyoo at cs.wpi.edu
Thu Jun 7 01:52:41 CEST 2007
On Wed, 6 Jun 2007, David Heiser wrote:
> or..
>
> def is_yes(question):
> while True:
> try:
> s = raw_input(question).lower()[0]
> if s == 'y':
> return True
> elif s == 'n':
> return False
> except:
> pass ## This traps the condition where a user just
> presses enter
> print '\nplease select y, n, yes, or no\n'
Hi David,
This does have a different functionality and is is more permissive than
the original code. What if the user types in "yoo-hoo"? The original
code would reject this, but the function above will treat it as as yes.
It does depend on what one wants.
Since there is no comment or documentation on is_yes() that says how it
should behave, I guess we can say that anything goes, but that's probably
a situation we should fix.
For this particular situation, I'd avoid the try/except block that is used
for catching array-out-of-bounds errors. If we do want the above
functionality, we can take advantage of string slicing to similar effect:
###################################################
def is_yes(question):
"""Asks for a response until the user presses something beginning
either with 'y' or 'n'. Returns True if 'y', False otherwise."""
while True:
s = raw_input(question).lower()
if s[:1] == 'y':
return True
elif s[:1] == 'n':
return False
print '\nplease select y, n, yes, or no\n'
###################################################
More information about the Tutor
mailing list