| |||||||||||
| |||||||||||
the while and else structure
All the languages we teach have if and else conditionals, and while loops. They're a necessary part of any language, accepted as something of a standard, and we teach them on all the fundamental courses. Uniquely, Python allows you to add an else clause onto the end of a while loop. Why? So that you can define a block of code that's to be run upon an exit from the loop caused by the loop's condition becoming false, but that's to be skipped over if the loop exits through a break statement or because of an exception. Here's an example. This program is going to loop, reading in people who are coming to your teenager's party. If you complete the data entry by pressing the "enter" key without entering another name, the <b>else</b> clause on the while is run and your party list is displayed. If you enter "parents" then the party plans are abandoned - you break out of the data entry loop and don't run the else block. running = 1 friends = [] while running: said = raw_input("Who's coming to the party? ") if said == "parents": print "Party plans abandoned" break if said == "": print "Data entry complete" running = 0 else: friends.append(said) else: print "Having a party for ", print friends print "program exiting" Let's see what that does when we run it earth-wind-and-fire:~/feb05 grahamellis$ python pywhi Who's coming to the party? Tom Who's coming to the party? Dick Who's coming to the party? Harry Who's coming to the party? Data entry complete Having a party for ['Tom', 'Dick', 'Harry'] program exiting earth-wind-and-fire:~/feb05 grahamellis$ python pywhi Who's coming to the party? Lisa Who's coming to the party? Leah Who's coming to the party? parents Party plans abandoned program exiting earth-wind-and-fire:~/feb05 grahamellis$ See also Python Programming course Please note that articles in this section of our
web site were current and correct to the best of our ability when published,
but by the nature of our business may go out of date quite quickly. The
quoting of a price, contract term or any other information in this area of
our website is NOT an offer to supply now on those terms - please check
back via our main web site
Related Material
Python - Conditionals and Loops resource index - Python Solutions centre home page You'll find shorter technical items at The Horse's Mouth and delegate's questions answered at the Opentalk forum. At Well House Consultants, we provide training courses on subjects such as Ruby, Perl, Python, Linux, C, C++, Tcl/Tk, Tomcat, PHP and MySQL. We're asked (and answer) many questions, and answers to those which are of general interest are published in this area of our site. | |||||||||||
PH: 0800 043 8225 or 01225 708225 • FAX: 0845 8382 405 or 01225 707126 • EMAIL: info@wellho.net • WEB: http://www.wellho.net • SKYPE: wellho | |||||||||||