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

The while Statement - 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

The while statement in Python supports repeated execution of a statement or block of statements that are controlled by a conditional expression. Here's the syntax for the while statement:

  while expression:
      statement(s
)

A while statement can also include an else clause, covered in "The else Clause on Loop Statements" on page 69, and break and continue statements, covered in "The break Statement" on page 68 and "The continue Statement" on page 68.

Here's a typical while statement:

  count = 0
 
while x > 0:
     
x = x // 2       # truncating division
     
count += 1 
  
print "The approximate log2 is", count

First, Python evaluates expression , which is known as the loop condition. If the condition is false, the while statement ends. If the loop condition is satisfied, the statement or statements that make up the loop body execute. When the loop body finishes executing, Python evaluates the loop condition again to check whether another iteration should execute. This process continues until the loop condition is false, at which point the while statement ends.

The loop body should contain code that eventually makes the loop condition false; otherwise, the loop will never end (unless an exception is raised or the loop body executes a break statement). A loop that is in a function's body also ends if a return statement executes in the loop body, since the whole function ends in this case.

The for Statement

The for statement in Python supports repeated execution of a statement, or block of statements, controlled by an iterable expression. Here's the syntax for the for statement:

  for target in iterable:
      statement(s
)

The in keyword is part of the syntax of the for statement and is distinct from the in operator, which tests membership. A for statement can also include an else clause, covered in "The else Clause on Loop Statements" on page 69, and break and continue statements, covered in "The break Statement" on page 68 and "The continue Statement" on page 68.

Here's a typical for statement:

  for letter in "ciao":
      print "give me a", letter, "..."

iterable  may be any Python expression suitable as an argument to built-in function iter, which returns an iterator object (explained in detail in the next section). In particular, any sequence is iterable. target  is normally an identifier that names the control variable of the loop; the for statement successively rebinds this variable to each item of the iterator, in order. The statement or statements that make up the loop body execute once for each item in iterable (unless the loop ends because an exception is raised or a break or return statement executes). Note that, since the loop body may contain a break statement to terminate the loop, this is one case in which you may want to use an unbounded iterable--one that, per se, would never cease yielding items.

You can also have a target with multiple identifiers, as with an unpacking assignment. In this case, the iterator's items must then be iterables, each with exactly as many items as there are identifiers in the target. For example, when d  is a dictionary, this is a typical way to loop on the items (key/value pairs) in d :

  for key, value in d.items():
      if not key or not value:     # keep only true keys and values
          del d[key]

The items method returns a list of key/value pairs, so we can use a for loop with two identifiers in the target to unpack each item into key and value.

When an iterator has a mutable underlying object, you must not alter that object during a for loop on it. For example, the previous example cannot use iteritems instead of items. iteritems returns an iterator whose underlying object is d, so the loop body cannot mutate d (by executing del d[key] ). items returns a list so that d is not the underlying object of the iterator; therefore, the loop body can mutate d. Specifically:

  • When looping on a list, do not insert, append, or delete items (rebinding an item at an existing index is OK).
  • When looping on a dictionary, do not add or delete items (rebinding the value for an existing key is OK).
  • When looping on a set, do not add or delete items (no alteration is permitted).

The control variable may be rebound in the loop body but is rebound again to the next item in the iterator at the next iteration of the loop. The loop body does not execute at all if the iterator yields no items. In this case, the control variable is not bound or rebound in any way by the for statement. If the iterator yields at least one item, however, when the loop statement terminates, the control variable remains bound to the last value to which the loop statement has bound it. The following code is therefore correct, as long as someseq is not empty:

  for x in someseq:
     
process(x)
  print "Last item processed was", x



 
 
>>> 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: