"How A Computer Looks at Your Program".">
  1. Computing

Beginning Python: Controlling the Flow

From , former About.com Guide

4 of 7

IF...ELIF...ELSE Loops - Part 1

Another means of controlling the flow is to say "If <some circumstance exists>: <do this>." Obviously, if the circumstance does not exist, the computer will ignore the lot. Sometimes, however, it is nice to have a "default setting" for the program's flow, an "else": If <a particular circumstance exists>: <do this> else: <do that>. The following templates and examples illustrate how these two loops are written:

 if <condition>: 
 <action to be taken> 
or
 if <condition>: 
 <action to be taken> 
 else: 
 <default action> 
 if c < 0: 
 print c 
 if animal == dog: 
 print "bow-wow" 
 else: 
 print "meow" 

You might think it a bit cludgy to have to write 'if...else' statements for every possible option. You would be right, and this is why Python has an additional, optional part of the 'if' loop: 'elif'. 'elif' is for the various options that fit neither the 'if' nor the else. The template and an example are as follows:

 if <1st condition>: 
 <action to be taken> 
 elif <2nd condition>: 
 <other action to be taken> 
 else: 
 <default action> 
 if animal == 'dog': 
 print "bow-wow" 
 elif animal == 'cat': 
 print "meow" 
 else: 
 print "cockadoodledoo!" 

©2013 About.com. All rights reserved.