1. Home
  2. Computing & Technology
  3. Python

Beginning Python: Controlling the Flow

From , former About.com Guide

5 of 7

IF...ELIF...ELSE Loops - Part 2

If one writes a series of 'if' conditions, the computer will work its way through each of them, performing the action of all that match. But when one uses 'if...elif...else', the computer treats the entire collection of conditions as a unit and only does the action of the first condition that matches.

In the series of 'if' statements below, all of the given conditions are true, so the program would perform each of the actions in turn. In the 'if...elif...else' series of statements, the computer will perform only the action associated with the first true condition, ignoring the rest.

c = 100

if c > 99:
     print "c is greater than 99."
if c < 200:
     print "c is less than 200."
if c <= 100:
     print "c is less than or equal to 100."
if c >= 100:
     print "c is greater than or equal to 100."
output:
c is greater than 99.
c is less than 200.
c is less than or equal to 100.
c is greater than or equal to 100.
c = 100

if c > 99:
     print "c is greater than 99."
elif c < 200:
     print "c is less than 200."
elif c <= 100:
     print "c is less than or equal to 100."
elif c >= 100:
     print "c is greater than or equal to 100."
else:
     print "The value of c is unclear."
output:
c is greater than 99.

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.