< BACKMake Note | BookmarkCONTINUE >
156135250194107072078175030179198180024228156016206217188240240204173120061000063012170099

if Statement

The standard if conditional statement follows this syntax:

					
 if
						expression:
    if_suite

				

If the expression is non-zero or true, then the statement suite is executed; otherwise, execution continues on the first statement after. "Suite" is the term used in Python to refer to a sub-block of code and can consist of single or multiple statements.

					
>>> if counter > 5:
…       print 'stopping after 5 iterations'
…       break

				

Python supports an else statement that is used with if in the following manner:

					
 if expression:
      if_suite
 else:
      else_suite

				

Python has an "else-if" statement named elif which has the following syntax:

					
 if
						expression1:
      if_suite
 elif
						expression2:
      elif_suite
 else:
      else_suite

				

Another surprise: There is no switch or case statement in Python. This may also seem strange and/or detracting at first, but a set of if-elif-else statements are not as "ugly" because of Python's clean syntax. If you really want to circumvent a set of chained if-elif-else statements, another elegant workaround is using a for loop (see below) to iterate through your list of possible "cases."

You can learn more about if, elif, and else statements in the conditional section of Chapter 8.


Last updated on 9/14/2001
Core Python Programming, © 2002 Prentice Hall PTR

< BACKMake Note | BookmarkCONTINUE >

© 2002, O'Reilly & Associates, Inc.