
September 1st, 2012, 09:57 PM
|
 |
Contributing User
|
|
|
|
Thank you for the clear description.
Here's one way
Code:
def monkeys():
if 'yes' != raw_input('Is that an animal?').lower():
return "get it outta' here then!"
if 'monkey' == raw_input('What kind?').lower():
return 'Oh, wow!'
return 'Never heard of it'
if '__main__' == __name__:
print monkeys()
else:
print 'use monkeys() function in this module'
Here's another way to write the logic in a style similar to your post. The essential change is that I've moved the "What kind?" question into one side of the test. The question arises depending on the first question.
Code:
if not ('yes' == raw_input('Is that an animal?').lower()):
print "get it outta' here then!"
else:
if 'monkey' == raw_input('What kind?').lower():
print 'Oh, wow!'
else:
print 'Never heard of it'
*Oh, I used a negative test for stylistic reasons.
Code:
# I rewrite
if condition: # poor style. "if" is physically far from "else"
many
lines
of
code
else:
fewer lines of code
# as
if not (condition): # put "else" close to "if"
fewer lines of code
else:
many
lines
of
code
**Oh, some people swear that a function should have one return. (Dykstra, in particular as I recall.) I happen to prefer short functions with few indentation levels. Multiple return statements don't scare me. Now the comefrom statement---that's another beast.
Last edited by b49P23TIvg : September 1st, 2012 at 10:13 PM.
|