On Sat, 12 Jun 2010 07:12:27 am Advertising Department wrote: > #!/Library/Frameworks/Python.framework/Versions/Current/bin/pythonw > """still thinking in imperative" > """
There is absolutely nothing wrong with writing imperative code. Python makes it easy to mix imperative, functional and object-oriented code in the same application, and in truth you'll soon find that they blend into each other so easily that sometimes it's hard to tell the difference. > ## obviously this is a bad construct. > ## Can someone suggest a pythonesque way of doing this? You have to explain what you are aiming to do. > def getid(): > response = raw_input('prompt') > if response not in [ "", "y", "Y", "yes"] : > getid() # ouch > print "continue working" > # do more stuff > # do more stuff You have comments "do more stuff" (repeated twice, so I suppose that means there is a LOT of more stuff) in a function called "getid". *That* is a bad programming construct, and not just in Python, and not because it is imperative. It is because the getid() function should do ONE THING -- get the id, and nothing else. You should separate the *user interface* from the *backend* (the engine). So you should have two functions: def getid(): """Return the id.""" return 123456789 # FIXME everybody has the same id... def ask_id(prompt): prompt = prompt + ' (Y/n) ' done = False while not done: response = raw_input(prompt) done = response.lower() in ["", "y", "yes", "n", "no"] return response.lower() in ["", "y", "yes"] And then put them together in your main program like this: def main(): if ask_id('Would you like an ID?'): x = getid() do_something_with_id(x) print "Continue working"... do_some_work() do_some_more_work() while ask_id('Would you like another ID?'): x = getid() do_something_else_with_id(x) print "Done now!" main() Hope this helps. -- Steven D'Aprano _______________________________________________ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor