Statements and Iterators in 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.

The print Statement

A print statement is denoted by the keyword print followed by zero or more expressions separated by commas. print is a handy, simple way to output values in text form, mostly for debugging purposes. print outputs each expression x  as a string that’s just like the result of calling str(x) (covered in str on page 157). print implicitly outputs a space between expressions, and implicitly outputs n after the last expression, unless the last expression is followed by a trailing comma (,). Here are some examples of print statements:

  letter = ‘c’
  print "give me a", letter, "…"      # prints: give me a c …
  answer = 42
  print "the answer is:", answer        # prints: the answer is: 42

The destination of print’s output is the file or file-like object that is the value of the stdout attribute of the sys module (covered in "The sys Module" on page 168). If you want to direct the output from a certain print statement to a specific file object f  (which must be open for writing), you can use the special syntax:

  print >>f, rest of print statement

(if f  is None, the destination is sys.stdout, just as it would be without the >>f ). You can also use the write or writelines methods of file objects, as covered in "Attributes and Methods of File Objects" on page 218. However, print is very simple to use, and simplicity is important in the common case where all you need are the simple output strategies that print supplies–in particular, this is often the case for the kind of simple output statements you may temporarily add to a program for debugging purposes. "The print Statement" on page 256 has more advice and examples concerning the use of print.

{mospagebreak title=Control Flow Statements}

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.

{mospagebreak title=The while Statement}

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

{mospagebreak title=Iterators}

An iterator is an object i such that you can call i.next() with no arguments. i.next() returns the next item of iterator i  or, when iterator i  has no more items, raises a StopIteration exception. When you write a class (see "Classes and Instances" on page 82), you can allow instances of the class to be iterators by defining such a method next. Most iterators are built by implicit or explicit calls to built-in function iter, covered in iter on page 163. Calling a generator also returns an iterator, as we’ll discuss in "Generators" on page 78.

The for statement implicitly calls iter to get an iterator. The following statement:

  for x in c:
     
statement(s)

is exactly equivalent to:

  _temporary_iterator = iter(c)
 
while True:
     
try: x = _temporary_iterator.next()
      except StopIteration: break
      statement(s)

where _temporary_iterator  is some arbitrary name that is not used elsewhere in the current scope.

Thus, if iter(c) returns an iterator i  such that
i.next() never raises StopIteration (an unbounded iterator), the loop for x  in c  never terminates (unless the statements in the loop body include suitable break or return statements, or raise or propagate exceptions). iter(c), in turn, calls special method c.__iter__() to obtain and return an iterator on c . I’ll talk more about the special method __iter__ in __iter__ on page 112.

Many of the best ways to build and manipulate iterators are found in standard library module itertools, covered in "The itertools Module" on page 183.

range and xrange

Looping over a sequence of integers is a common task, so Python provides built-in functions range and xrange to generate and return integer sequences. The simplest way to loop n  times in Python is:

  for i in xrange(n):
      statement(s
)

range(x) returns a list whose items are consecutive integers from 0 (included) up to x  (excluded).
range(x, y) returns a list whose items are consecutive integers from x  (included) up to y (excluded). The result is the empty list if x  is greater than or equal to y . range(x, y, step) returns a list of integers from x  (included) up to y  (excluded), such that the difference between each two adjacent items in the list is step. If step  is less than 0, range counts down from x  to y . range returns the empty list when x  is greater than or equal to y  and step  is greater than 0, or when x  is less than or equal to y  and step is less than 0. When step  equals 0, range raises an exception.

While range returns a normal list object, usable for all purposes, xrange returns a special-purpose object, specifically intended for use in iterations like the for statement shown previously (unfortunately, to keep backward compatibility with old versions of Python, xrange does not return an iterator, as would be natural in today’s Python; however, you can easily obtain such an iterator, if you need one, by calling iter(xrange(…))). The special-purpose object xrange returns consumes less memory (for wide ranges, much less memory) than the list object range returns, but the overhead of looping on the special-purpose object is slightly higher than that of looping on a list. Apart from performance and memory consumption issues, you can use range wherever you could use xrange, but not vice versa. For example:

  >>> print range(1, 5)
  
[1, 2, 3, 4]
 
>>> print xrange(1, 5)
 
xrange(1, 5)

Here, range returns a perfectly ordinary list, which displays quite normally, but xrange returns a special-purpose object, which displays in its own special way.

Please check back next week for the continuation of this article. 

[gp-comments width="770" linklove="off" ]

antalya escort bayan antalya escort bayan Antalya escort diyarbakir escort