Home arrow Python arrow Page 2 - Statements and Iterators in Python

Control Flow Statements - Python

In this sixth part of a nine-part series on the Python language, you will learn about the print statement, control flow statements, and more. It is excerpted from chapter four of the book Python in a Nutshell, Second Edition, written by Alex Martelli (O'Reilly; ISBN: 0596100469). Copyright 2007 O'Reilly Media, Inc. All rights reserved. Used with permission from the publisher. Available from booksellers or direct from O'Reilly Media.

TABLE OF CONTENTS:
  1. Statements and Iterators in Python
  2. Control Flow Statements
  3. The while Statement
  4. Iterators
By: O'Reilly Media
Rating: starstarstarstarstar / 2
October 16, 2008

print this article
SEARCH DEV SHED

TOOLS YOU CAN USE

advertisement

A programs control flow is the order in which the program's code executes. The control flow of a Python program is regulated by conditional statements, loops, and function calls. (This section covers the if statement and for and while loops; functions are covered in "Functions" on page 70.) Raising and handling exceptions also affects control flow; exceptions are covered in Chapter 6.

The if Statement

Often, you need to execute some statements only if some condition holds, or choose statements to execute depending on several mutually exclusive conditions. The Python compound statement if, comprising if, elif, and else clauses, lets you conditionally execute blocks of statements. Here's the syntax for the if statement:

  if expression:
      statement(s)
 
elif expression:
     
statement(s)
 
elif expression:
      statement(s
  
...
  else:
     
statement(s)

The elif and else clauses are optional. Note that, unlike some languages, Python does not have a switch statement. Use if, elif, and else for all conditional processing.

  Here's a typical if statement with all three kinds of clauses:

  if x < 0: print "x is negative"
  elif x % 2: print "x is positive and odd"
  else: print "x is even and non-negative"

When there are multiple statements in a clause (i.e., the clause controls a block of statements), the statements are placed on separate logical lines after the line containing the clause's keyword (known as the header line of the clause), indented rightward from the header line. The block terminates when the indentation returns to that of the clause header (or further left from there). When there is just a single simple statement, as here, it can follow the : on the same logical line as the header, but it can also be on a separate logical line, immediately after the header line and indented rightward from it. Most Python programmers prefer the separate-line style, with four-space indents for the guarded statements. Such a style is considered more general and more readable.

  if x < 0:
     
print "x is negative"
  elif x % 2:
     
print "x is positive and odd"
  else:
     
print "x is even and non-negative"

You can use any Python expression as the condition in an if or elif clause. Using an expression this way is known as using it "in a Boolean context." In a Boolean context, any value is taken as either true or false. As mentioned earlier, any nonzero number or nonempty container (string, tuple, list, dictionary, set) evaluates as true; zero (of any numeric type), None, and empty containers evaluate as false. When you want to test a value x in a Boolean context, use the following coding style:

  if x:

This is the clearest and most Pythonic form. Do not use any of the following:

  if x is True:
  if x == True:
  if bool(x):

There is a crucial difference between saying that an expression returns True (meaning the expression returns the value 1 with the bool type) and saying that an expression evaluates as true (meaning the expression returns any result that is true in a Boolean context). When testing an expression, you care about the latter condition, not the former.

If the expression for the if clause evaluates as true, the statements following the if clause execute, and the entire if statement ends. Otherwise, Python evaluates the expressions for each elif clause, in order. The statements following the first elif clause whose condition evaluates as true, if any, execute, and the entire if statement ends. Otherwise, if an else clause exists, the statements following it execute.



 
 
>>> More Python Articles          >>> More By O'Reilly Media
 

blog comments powered by Disqus
escort Bursa Bursa escort Antalya eskort
   

PYTHON ARTICLES

- Python Big Data Company Gets DARPA Funding
- Python 32 Now Available
- Final Alpha for Python 3.2 is Released
- Python 3.1: String Formatting
- Python 3.1: Strings and Quotes
- Python 3.1: Programming Basics and Strings
- Tuples and Other Python Object Types
- The Dictionary Python Object Type
- String and List Python Object Types
- Introducing Python Object Types
- Mobile Programming using PyS60: Advanced UI ...
- Nested Functions in Python
- Python Parameters, Functions and Arguments
- Python Statements and Functions
- Statements and Iterators in Python

Developer Shed Affiliates

 


Dev Shed Tutorial Topics: