IF ELSE Loop (this is for your understanding)
Posted by JanWan
Last Updated: July 06, 2012
  885

IF ELSE Loop

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!" 

J.W. PRODUCTION

   
  
 
 
   

 
 
Great Article!