1. Home
  2. Computing & Technology
  3. Python

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

Explore Python
About.com Special Features

Holiday Central

What to eat, where to go, fun things to do and how to save money on the perfect gifts. More >

Family Tech Center

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

  1. Home
  2. Computing & Technology
  3. Python

©2009 About.com, a part of The New York Times Company.

All rights reserved.