Text stringlengths 1 9.41k |
|---|
in slicing extensions), so time will tell if it becomes widespread enough to challenge pass and None in these roles.
###### continue
The continue statement causes an immediate jump to the top of a loop. |
It also sometimes lets you avoid statement nesting. The next example uses continue to skip odd
numbers. This code prints all even numbers less than 10 and greater than or equal to
0. |
Remember, 0 means false and % is the remainder of division operator, so this loop
counts down to 0, skipping numbers that aren’t multiples of 2 (it prints 8 6 4 2 0):
```
x = 10
while x:
x = x−1 # Or, x -= 1
if x % 2 != 0: continue # Odd? |
-- skip print
print(x, end=' ')
```
Because continue jumps to the top of the loop, you don’t need to nest the print statement inside an if test; the print is only reached if the continue is not run. |
If this sounds
similar to a “goto” in other languages, it should. |
Python has no “goto” statement, but
because continue lets you jump about in a program, many of the warnings about readability and maintainability you may have heard about goto apply. |
`continue should`
probably be used sparingly, especially when you’re first getting started with Python.
For instance, the last example might be clearer if the print were nested under the if:
```
x = 10
while x:
x = x−1
if x % 2 == 0: # Even? |
-- print
print(x, end=' ')
###### break
```
The break statement causes an immediate exit from a loop. |
Because the code that follows it in the loop is not executed if the break is reached, you can also sometimes avoid
nesting by including a break. |
For example, here is a simple interactive loop (a variant
of a larger example we studied in Chapter 10) that inputs data with input (known as
```
raw_input in Python 2.6) and exits when the user enters “stop” for the name request:
>>> while True:
... |
name = input('Enter name:')
... if name == 'stop': break
... age = input('Enter age: ')
... |
print('Hello', name, '=>', int(age) ** 2)
...
Enter name:mel
Enter age: 40
```
**|**
-----
```
Hello mel => 1600
Enter name:bob
Enter age: 30
Hello bob => 900
Enter name:stop
```
Notice how this code converts the age input to an integer with int before raising it to
the second power; as you’ll reca... |
In Chapter 35, you’ll see that input also raises an exception at end-of-file (e.g.,
if the user types Ctrl-Z or Ctrl-D); if this matters, wrap input in try statements.
###### Loop else
When combined with the loop else clause, the break statement can often eliminate the
need for the search status flags used in other l... |
For instance, the following
piece of code determines whether a positive integer y is prime by searching for factors
greater than 1:
```
x = y // 2 # For some y > 1
while x > 1:
if y % x == 0: # Remainder
print(y, 'has factor', x)
break # Skip else
x -= 1
... |
This way, the loop else clause can assume that it will be executed
only if no factor is found; if you don’t hit the break, the number is prime.
The loop else clause is also run if the body of the loop is never executed, as you don’t
run a break in that event either; in a while loop, this happens if the test in the hea... |
Thus, in the preceding example you still get the “is prime” message
if x is initially less than or equal to 1 (for instance, if y is 2).
This example determines primes, but only informally so. |
Numbers less
than 2 are not considered prime by the strict mathematical definition.
To be really picky, this code also fails for negative numbers and succeeds
for floating-point numbers with no decimal digits. |
Also note that its
code must use // instead of / in Python 3.0 because of the migration
of / to “true division,” as described in Chapter 5 (we need the initial
division to truncate remainders, not retain them!). |
If you want to experiment with this code, be sure to see the exercise at the end of
Part IV, which wraps it in a function for reuse.
**|** **f**
-----
###### More on the loop else
Because the loop else clause is unique to Python, it tends to perplex some newcomers.
In general terms, the loop else provides explicit... |
We might code such
a task this way:
```
found = False
while x and not found:
if match(x[0]): # Value at front?
print('Ni')
found = True
else:
x = x[1:] # Slice off front and repeat
if not found:
print('not found')
```
Here, we initialize, set, and later test a flag ... |
This is valid Python code, and it does work; however, this is exactly the sort of
structure that the loop else clause is there to handle. |
Here’s an else equivalent:
```
while x: # Exit when x empty
if match(x[0]):
print('Ni')
break # Exit, go around else
x = x[1:]
else:
print('Not found') # Only here if exhausted x
```
This version is more concise. |
The flag is gone, and we’ve replaced the if test at the loop
end with an else (lined up vertically with the word while). |
Because the break inside the
main part of the while exits the loop and goes around the else, this serves as a more
structured way to catch the search-failure case.
Some readers might have noticed that the prior example’s else clause could be replaced
with a test for an empty x after the loop (e.g., if not x:). |
Although that’s true in this
example, the else provides explicit syntax for this coding pattern (it’s more obviously
a search-failure clause here), and such an explicit empty test may not apply in some
cases. |
The loop else becomes even more useful when used in conjunction with the
```
for loop—the topic of the next section—because sequence iteration is not under your
```
control.
**|**
-----
###### for Loops
The for loop is a generic sequence iterator in Python: it can step through the items in
any ordered sequence ob... |
The for statement works on strings, lists, tuples, other
built-in iterables, and new objects that we’ll see how to create later with classes. |
We
met it in brief when studying sequence object types; let’s expand on its usage more
formally here.
###### General Format
The Python for loop begins with a header line that specifies an assignment target (or
targets), along with the object you want to step through. |
The header is followed by a
block of (normally indented) statements that you want to repeat:
**|** **f**
-----
```
for <target> in <object>: # Assign object items to target
<statements> # Repeated loop body: use target
else:
<statements> # If we didn't hit a 'break'
```
When P... |
The loop body typically uses the
assignment target to refer to the current item in the sequence as though it were a cursor
stepping through the sequence.
The name used as the assignment target in a for header line is usually a (possibly new)
variable in the scope where the for statement is coded. |
There’s not much special about
it; it can even be changed inside the loop’s body, but it will automatically be set to the
next item in the sequence when control returns to the top of the loop again. |
After the
loop this variable normally still refers to the last item visited, which is the last item in
the sequence unless the loop exits with a break statement.
The for statement also supports an optional else block, which works exactly as it does
in a while loop—it’s executed if the loop exits without running into a... |
The break and continue statements
introduced earlier also work the same in a for loop as they do in a while. |
The for loop’s
complete format can be described this way:
```
for <target> in <object>: # Assign object items to target
<statements>
if <test>: break # Exit loop now, skip else
if <test>: continue # Go to top of loop now
else:
<statements> # If we didn't hit a 'break'
... |
In our
first example, for instance, we’ll assign the name x to each of the three items in a list in
turn, from left to right, and the print statement will be executed for each. |
Inside the
```
print statement (the loop body), the name x refers to the current item in the list:
>>> for x in ["spam", "eggs", "ham"]:
... |
print(x, end=' ')
...
spam eggs ham
```
The next two examples compute the sum and product of all the items in a list. |
Later in
this chapter and later in the book we’ll meet tools that apply operations such as + and
```
* to items in a list automatically, but it’s usually just as easy to use a for:
```
**f** **|**
-----
```
>>> sum = 0
>>> for x in [1, 2, 3, 4]:
... |
sum = sum + x
...
>>> sum
10
>>> prod = 1
>>> for item in [1, 2, 3, 4]: prod *= item
...
>>> prod
24
###### Other data types
```
Any sequence works in a for, as it’s a generic tool. |
For example, for loops work on
strings and tuples:
```
>>> S = "lumberjack"
>>> T = ("and", "I'm", "okay")
```
`>>> for x in S: print(x, end=' ')` _# Iterate over a string_
```
...
l u m b e r j a c k
```
`>>> for x in T: print(x, end=' ')` _# Iterate over a tuple_
```
...
and I'm okay
```
In fact, as we... |
This is just another case of the tuple-unpacking assignment we studied_
in Chapter 11 at work. |
Remember, the for loop assigns items in the sequence object
to the target, and assignment works the same everywhere:
```
>>> T = [(1, 2), (3, 4), (5, 6)]
```
`>>> for (a, b) in T:` _# Tuple assignment at work_
```
... |
print(a, b)
...
1 2
3 4
5 6
```
Here, the first time through the loop is like writing (a,b) = (1,2), the second time is
like writing (a,b) = (3,4), and so on. |
The net effect is to automatically unpack the
current tuple on each iteration.
This form is commonly used in conjunction with the zip call we’ll meet later in this
chapter to implement parallel traversals. |
It also makes regular appearances in conjunction with SQL databases in Python, where query result tables are returned as sequences
**|** **f**
-----
of sequences like the list used here—the outer list is the database table, the nested tuples
are the rows within the table, and tuple assignment extracts columns.
Tup... |
print(key, '=>', D[key])` _# Use dict keys iterator and index_
```
...
a => 1
c => 3
b => 2
>>> list(D.items())
[('a', 1), ('c', 3), ('b', 2)]
>>> for (key, value) in D.items():
```
`... |
print(key, '=>', value)` _# Iterate over both keys and values_
```
...
a => 1
c => 3
b => 2
```
It’s important to note that tuple assignment in for loops isn’t a special case; any assignment target works syntactically after the word for. |
Although we can always assign
manually within the loop to unpack:
```
>>> T
[(1, 2), (3, 4), (5, 6)]
>>> for both in T:
```
`... a, b = both` _# Manual assignment equivalent_
```
... |
print(a, b)
...
1 2
3 4
5 6
```
Tuples in the loop header save us an extra step when iterating through sequences of
sequences. |
As suggested in Chapter 11, even nested structures may be automatically
unpacked this way in a for:
`>>> ((a, b), c) = ((1, 2), 3)` _# Nested sequences work too_
```
>>> a, b, c
(1, 2, 3)
>>> for ((a, b), c) in [((1, 2), 3), ((4, 5), 6)]: print(a, b, c)
...
1 2 3
4 5 6
```
**f** **|**
-----
But this is... |
Any nested sequence structure may be unpacked this way,
just because sequence assignment is so generic:
```
>>> for ((a, b), c) in [([1, 2], 3), ['XY', 6]]: print(a, b, c)
...
1 2 3
X Y 6
###### Python 3.0 extended sequence assignment in for loops
```
In fact, because the loop variable in a for loop can reall... |
Really, this isn’t a special
case either, but simply a new assignment form in 3.0 (as discussed in Chapter 11);
because it works in assignment statements, it automatically works in for loops.
Consider the tuple assignment form introduced in the prior section. |
A tuple of values
is assigned to a tuple of names on each iteration, exactly like a simple assignment
statement:
`>>> a, b, c = (1, 2, 3)` _# Tuple assignment_
```
>>> a, b, c
(1, 2, 3)
```
`>>> for (a, b, c) in [(1, 2, 3), (4, 5, 6)]:` _# Used in for loop_
```
... |
print(a, b, c)
...
1 2 3
4 5 6
```
In Python 3.0, because a sequence can be assigned to a more general set of names with
a starred name to collect multiple items, we can use the same syntax to extract parts of
nested sequences in the for loop:
`>>> a, *b, c = (1, 2, 3, 4)` _# Extended seq assignment_
```
>>> ... |
print(a, b, c)
...
1 [2, 3] 4
5 [6, 7] 8
```
In practice, this approach might be used to pick out multiple columns from rows of
data represented as nested sequences. |
In Python 2.X starred names aren’t allowed, but
you can achieve similar effects by slicing. |
The only difference is that slicing returns a
type-specific result, whereas starred names always are assigned lists:
`>>> for all in [(1, 2, 3, 4), (5, 6, 7, 8)]:` _# Manual slicing in 2.6_
```
... |
a, b, c = all[0], all[1:3], all[3]
... |
print(a, b, c)
```
**|** **f**
-----
```
...
1 (2, 3) 4
5 (6, 7) 8
```
See Chapter 11 for more on this assignment form.
###### Nested for loops
Now let’s look at a for loop that’s a bit more sophisticated than those we’ve seen so
far. |
The next example illustrates statement nesting and the loop else clause in a for.
Given a list of objects (items) and a list of keys (tests), this code searches for each key
in the objects list and reports on the search’s outcome:
`>>> items = ["aaa", 111, (4, 5), 2.01]` _# A set of objects_
`>>> tests = [(4, 5), 3.14... |
for item in items:` _# For all items_
`... if item == key:` _# Check for match_
```
... print(key, "was found")
... break
... else:
... |
print(key, "not found!")
...
(4, 5) was found
3.14 not found!
```
Because the nested if runs a break when a match is found, the loop else clause can
assume that if it is reached, the search has failed. |
Notice the nesting here. When this
code runs, there are two loops going at the same time: the outer loop scans the keys
list, and the inner loop scans the items list for each key. |
The nesting of the loop else
clause is critical; it’s indented to the same level as the header line of the inner for loop,
so it’s associated with the inner loop, not the if or the outer for.
Note that this example is easier to code if we employ the in operator to test membership.
Because in implicitly scans an object... |
if key in items:` _# Let Python check for a match_
```
... print(key, "was found")
... else:
... |
print(key, "not found!")
...
(4, 5) was found
3.14 not found!
```
In general, it’s a good idea to let Python do as much of the work as possible (as in this
solution) for the sake of brevity and performance.
The next example performs a typical data-structure task with a for—collecting common items in two sequenc... |
It’s roughly a simple set intersection routine;
after the loop runs, res refers to a list that contains all the items found in seq1 and seq2:
**f** **|**
-----
```
>>> seq1 = "spam"
>>> seq2 = "scam"
>>>
```
`>>> res = []` _# Start empty_
`>>> for x in seq1:` _# Scan first sequence_
`... |
if x in seq2:` _# Common item?_
`... |
res.append(x)` _# Add to result end_
```
...
>>> res
['s', 'a', 'm']
```
Unfortunately, this code is equipped to work only on two specific variables: seq1 and
```
seq2. |
It would be nice if this loop could somehow be generalized into a tool you could
```
use more than once. |
As you’ll see, that simple idea leads us to functions, the topic of
the next part of the book.
###### Why You Will Care: File Scanners
In general, loops come in handy anywhere you need to repeat an operation or process
something more than once. |
Because files contain multiple characters and lines, they
are one of the more typical use cases for loops. |
To load a file’s contents into a string all
at once, you simply call the file object’s read method:
```
file = open('test.txt', 'r') # Read contents into a string
print(file.read())
```
But to load a file in smaller pieces, it’s common to code either a while loop with breaks
on end-of-file, or a for loop. |
To read by characters, either of the following codings will
suffice:
```
file = open('test.txt')
while True:
char = file.read(1) # Read by character
if not char: break
print(char)
for char in open('test.txt').read():
print(char)
```
The for loop here also processes each characte... |
To read by lines or blocks instead, you can use while loop
code like this:
```
file = open('test.txt')
while True:
line = file.readline() # Read line by line
if not line: break
print(line, end='') # Line already has a \n
file = open('test.txt', 'rb')
while True:
chunk = fil... |
It’s generally simpler to code and
quicker to run than a while, so it’s the first tool you should reach for whenever you
need to step through a sequence. |
But there are also situations where you will need to
iterate in more specialized ways. For example, what if you need to visit every second
or third item in a list, or change the list along the way? |
How about traversing more than
one sequence in parallel, in the same for loop?
You can always code such unique iterations with a while loop and manual indexing,
but Python provides two built-ins that allow you to specialize the iteration in a for:
- The built-in range function produces a series of successively highe... |
Let’s look at
each of these built-ins in turn.
**|**
-----
###### Counter Loops: while and range
The range function is really a general tool that can be used in a variety of contexts.
Although it’s used most often to generate indexes in a for, you can use it anywhere you
need a list of integers. |
In Python 3.0, range is an iterator that generates items on demand,
so we need to wrap it in a list call to display its results all at once (more on iterators
in Chapter 14):
```
>>> list(range(5)), list(range(2, 5)), list(range(0, 10, 2))
([0, 1, 2, 3, 4], [2, 3, 4], [0, 2, 4, 6, 8])
```
With one argument, range ... |
If you pass in two arguments, the first is taken as the lower bound.
An optional third argument can give a step; if it is used, Python adds the step to each
successive integer in the result (the step defaults to 1). |
Ranges can also be nonpositive
and nonascending, if you want them to be:
```
>>> list(range(−5, 5))
[−5, −4, −3, −2, −1, 0, 1, 2, 3, 4]
>>> list(range(5, −5, −1))
[5, 4, 3, 2, 1, 0, −1, −2, −3, −4]
```
Although such range results may be useful all by themselves, they tend to come in most
handy within for loops... |
For one thing, they provide a simple way to repeat an action
a specific number of times. |
To print three lines, for example, use a range to generate
the appropriate number of integers; for loops force results from range automatically in
3.0, so we don’t need list here:
```
>>> for i in range(3):
... |
print(i, 'Pythons')
...
0 Pythons
1 Pythons
2 Pythons
range is also commonly used to iterate over a sequence indirectly. |
The easiest and fastest
```
way to step through a sequence exhaustively is always with a simple for, as Python
handles most of the details for you:
```
>>> X = 'spam'
```
`>>> for item in X: print(item, end=' ')` _# Simple iteration_
```
...
s p a m
```
Internally, the for loop handles the details of the itera... |
If you really need to take over the indexing logic explicitly, you can do it with
a while loop:
```
>>> i = 0
```
`>>> while i < len(X):` _# while loop iteration_
```
... |
print(X[i], end=' ')
... |
i += 1
```
**|** **f**
-----
```
...
s p a m
```
You can also do manual indexing with a for, though, if you use range to generate a list
of indexes to iterate through. |
It’s a multistep process, but it’s sufficient to generate
offsets, rather than the items at those offsets:
```
>>> X
'spam'
```
`>>> len(X)` _# Length of string_
```
4
```
`>>> list(range(len(X)))` _# All legal offsets into X_
```
[0, 1, 2, 3]
>>>
```
`>>> for i in range(len(X)): print(X[i], end=' ')` _# M... |
It’s also
more work than we need to do. |
Unless you have a special indexing requirement, you’re
always better off using the simple for loop form in Python—as a general rule, use for
instead of while whenever possible, and don’t use range calls in for loops except as a
last resort. |
This simpler solution is better:
`>>> for item in X: print(item)` _# Simple iteration_
```
...
```
However, the coding pattern used in the prior example does allow us to do more specialized sorts of traversals. |
For instance, we can skip items as we go:
```
>>> S = 'abcdefghijk'
>>> list(range(0, len(S), 2))
[0, 2, 4, 6, 8, 10]
>>> for i in range(0, len(S), 2): print(S[i], end=' ')
...
a c e g i k
```
Here, we visit every second item in the string S by stepping over the generated range
list. |
To visit every third item, change the third range argument to be 3, and so on. |
In
effect, using range this way lets you skip items in loops while still retaining the simplicity
of the for loop construct.
Still, this is probably not the ideal best-practice technique in Python today. |
If you really
want to skip items in a sequence, the extended three-limit form of the _slice expres-_
_sion, presented in Chapter 7, provides a simpler route to the same goal. |
To visit every_
second character in S, for example, slice with a stride of 2:
**|**
-----
```
>>> S = 'abcdefghijk'
>>> for c in S[::2]: print(c, end=' ')
...
a c e g i k
```
The result is the same, but substantially easier for you to write and for others to read.
The only real advantage to using range her... |
Suppose, for example, that you need to add 1
to every item in a list. |
You can try this with a simple for loop, but the result probably
won’t be exactly what you want:
```
>>> L = [1, 2, 3, 4, 5]
>>> for x in L:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.