Python
  Home arrow Python arrow Page 3 - Statements and Iterators in Python
Dev Shed Forums  
Administration  
AJAX  
Apache  
BrainDump  
DHTML  
Flash  
Java  
JavaScript  
Multimedia  
MySQL  
Oracle  
Perl  
PHP  
Practices  
Python  
Reviews  
Security  
Smartphone Development  
Style-Sheets  
Web Services  
XML  
Zend  
Zope  
Mobile Linux  
App Generation ROI  
IBM® developerWorks  
Forums Sitemap  
E-Commerce Hosting  
Linux Web Hosting  
Managed Hosting  
Small Business Hosting  
VPS Hosting  
Weekly Newsletter

 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid  
Request Media Kit
Contact Us  
Site Map  
Privacy Policy  
Support  
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
Google.com  
PYTHON

Statements and Iterators in Python
By: O'Reilly Media
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: starstarstarstarstar / 1
    2008-10-16


    Table of Contents:
  • Statements and Iterators in Python
  • Control Flow Statements
  • The while Statement
  • Iterators

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      error-file:tidyout.log Del.ici.ous error-file:tidyout.log Digg
      error-file:tidyout.log Blink error-file:tidyout.log Simpy
      error-file:tidyout.log Google error-file:tidyout.log Spurl
      error-file:tidyout.log Y! MyWeb error-file:tidyout.log Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article

     
     
    ADVERTISEMENT


    Statements and Iterators in Python - The while Statement
    ( Page 3 of 4 )

    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
     

       

    PYTHON ARTICLES

    - 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
    - Sequences and Sets in Python
    - Python Expressions and Operators
    - Dictionaries, Variables and Statements in Py...
    - Data Types in Python
    - The Python Language
    - SSH with Twisted





    © 2003-2009 by Developer Shed. All rights reserved. DS Cluster 6 Hosted by Hostway
    For more Enterprise Application Development news, visit eWeek