Text stringlengths 1 9.41k |
|---|
How is a statement normally terminated in Python?
3. How are the statements in a nested block of code normally associated in Python?
4. How can you make a single statement span multiple lines?
5. |
How can you code a compound statement on a single line?
6. Is there any valid reason to type a semicolon at the end of a statement in Python?
7. What is a try statement for?
8. |
What is the most common coding mistake among Python beginners?
**|**
-----
###### Test Your Knowledge: Answers
1. |
C-like languages require parentheses around the tests in some statements, semicolons at the end of each statement, and braces around a nested block of code.
2. |
The end of a line terminates the statement that appears on that line. |
Alternatively,
if more than one statement appears on the same line, they can be terminated with
semicolons; similarly, if a statement spans many lines, you must terminate it by
closing a bracketed syntactic pair.
3. |
The statements in a nested block are all indented the same number of tabs or spaces.
4. |
A statement can be made to span many lines by enclosing part of it in parentheses,
square brackets, or curly braces; the statement ends when Python sees a line that
contains the closing part of the pair.
5. |
The body of a compound statement can be moved to the header line after the colon,
but only if the body consists of only noncompound statements.
6. |
Only when you need to squeeze more than one statement onto a single line of code.
Even then, this only works if all the statements are noncompound, and it’s discouraged because it can lead to code that is difficult to read.
7. |
The try statement is used to catch and recover from exceptions (errors) in a Python
script. It’s usually an alternative to manually checking for errors in your code.
8. |
Forgetting to type the colon character at the end of the header line in a compound
statement is the most common beginner’s mistake. |
If you haven’t made it yet, you
probably will soon!
**|**
-----
-----
###### CHAPTER 11
### Assignments, Expressions, and Prints
Now that we’ve had a quick introduction to Python statement syntax, this chapter
begins our in-depth tour of specific Python statements. |
We’ll begin with the basics:
assignment statements, expression statements, and print operations. |
We’ve already
seen all of these in action, but here we’ll fill in important details we’ve skipped so far.
Although they’re fairly simple, as you’ll see, there are optional variations for each of
these statement types that will come in handy once you begin writing real Python
programs.
###### Assignment Statements
We’... |
In its basic form, you write the target of an assignment on the left of an equals
sign, and the object to be assigned on the right. |
The target on the left may be a name
or object component, and the object on the right can be an arbitrary expression that
computes an object. |
For the most part, assignments are straightforward, but here are
a few properties to keep in mind:
- Assignments create object references. |
As discussed in Chapter 6, Python assignments store references to objects in names or data structure components. They
always create references to objects instead of copying the objects. |
Because of that,
Python variables are more like pointers than data storage areas.
- Names are created when first assigned. |
Python creates a variable name the first
time you assign it a value (i.e., an object reference), so there’s no need to predeclare
names ahead of time. |
Some (but not all) data structure slots are created when
assigned, too (e.g., dictionary entries, some object attributes). |
Once assigned, a
name is replaced with the value it references whenever it appears in an expression.
- Names must be assigned before being referenced. |
It’s an error to use a name
to which you haven’t yet assigned a value. |
Python raises an exception if you try,
rather than returning some sort of ambiguous default value; if it returned a default
instead, it would be more difficult for you to spot typos in your code.
-----
- Some operations perform assignments implicitly. |
In this section we’re concerned with the = statement, but assignment occurs in many contexts in Python.
For instance, we’ll see later that module imports, function and class definitions,
```
for loop variables, and function arguments are all implicit assignments. |
Because
```
assignment works the same everywhere it pops up, all these contexts simply bind
names to object references at runtime.
###### Assignment Statement Forms
Although assignment is a general and pervasive concept in Python, we are primarily
interested in assignment statements in this chapter. |
Table 11-1 illustrates the different
assignment statement forms in Python.
_Table 11-1. |
Assignment statement forms_
**Operation** **Interpretation**
`spam = 'Spam'` Basic form
`spam, ham = 'yum', 'YUM'` Tuple assignment (positional)
`[spam, ham] = ['yum', 'YUM']` List assignment (positional)
`a, b, c, d = 'spam'` Sequence assignment, generalized
`a, *b = 'spam'` Extended sequence unpacking (Python... |
In fact, you could get all your work done with this
basic form alone. |
The other table entries represent special forms that are all optional,
but that programmers often find convenient in practice:
_Tuple- and list-unpacking assignments_
The second and third forms in the table are related. |
When you code a tuple or list
on the left side of the =, Python pairs objects on the right side with targets on the
left by position and assigns them from left to right. |
For example, in the second line
of Table 11-1, the name spam is assigned the string 'yum', and the name ham is bound
to the string 'YUM'. |
In this case Python internally makes a tuple of the items on the
right, which is why this is called tuple-unpacking assignment.
_Sequence assignments_
In recent versions of Python, tuple and list assignments have been generalized into
instances of what we now call sequence assignment—any sequence of names can
be assign... |
We can even mix and match the types of the sequences involved. |
The
fourth line in Table 11-1, for example, pairs a tuple of names with a string of
characters: a is assigned 's', b is assigned 'p', and so on.
**|**
-----
_Extended sequence unpacking_
In Python 3.0, a new form of sequence assignment allows us to be more flexible in
how we select portions of a sequence to assign. |
The fifth line in Table 11-1, for
example, matches a with the first character in the string on the right and b with the
rest: a is assigned 's', and b is assigned 'pam'. |
This provides a simpler alternative
to assigning the results of manual slicing operations.
_Multiple-target assignments_
The sixth line in Table 11-1 shows the multiple-target form of assignment. |
In this
form, Python assigns a reference to the same object (the object farthest to the right)
to all the targets on the left. |
In the table, the names spam and ham are both assigned
references to the same string object, 'lunch'. |
The effect is the same as if we had
coded ham = 'lunch' followed by spam = ham, as ham evaluates to the original string
object (i.e., not a separate copy of that object).
_Augmented assignments_
The last line in Table 11-1 is an example of augmented assignment—a shorthand
that combines an expression and an assignment i... |
Saying spam +=
```
42, for example, has the same effect as spam = spam + 42, but the augmented form
```
requires less typing and is generally quicker to run. |
In addition, if the subject is
mutable and supports the operation, an augmented assignment may run even
quicker by choosing an in-place update operation instead of an object copy. |
There
is one augmented assignment statement for every binary expression operator in
Python.
###### Sequence Assignments
We’ve already used basic assignments in this book. |
Here are a few simple examples of
sequence-unpacking assignments in action:
```
% python
>>> nudge = 1
>>> wink = 2
```
`>>> A, B = nudge, wink` _# Tuple assignment_
`>>> A, B` _# Like A = nudge; B = wink_
```
(1, 2)
```
`>>> [C, D] = [nudge, wink]` _# List assignment_
```
>>> C, D
(1, 2)
```
Notice that... |
Python pairs the values in the tuple on the
right side of the assignment operator with the variables in the tuple on the left side and
assigns the values one at a time.
Tuple assignment leads to a common coding trick in Python that was introduced in a
solution to the exercises at the end of Part II. |
Because Python creates a temporary tuple
that saves the original values of the variables on the right while the statement runs,
**|**
-----
unpacking assignments are also a way to swap two variables’ values without creating
a temporary variable of your own—the tuple on the right remembers the prior values
of the va... |
You can assign a tuple of values to a list of variables, a string of characters
to a tuple of variables, and so on. |
In all cases, Python assigns items in the sequence on
the right to variables in the sequence on the left by position, from left to right:
`>>> [a, b, c] = (1, 2, 3)` _# Assign tuple of values to list of names_
```
>>> a, c
(1, 3)
```
`>>> (a, b, c) = "ABC"` _# Assign string of characters to tuple_
```
>>> a, c
... |
This is a more general concept that we will explore in
Chapters 14 and 20.
###### Advanced sequence assignment patterns
Although we can mix and match sequence types around the = symbol, we must have
the same number of items on the right as we have variables on the left, or we’ll get an
error. |
Python 3.0 allows us to be more general with extended unpacking syntax, described in the next section. |
But normally, and always in Python 2.X, the number of
items in the assignment target and subject must match:
```
>>> string = 'SPAM'
```
`>>> a, b, c, d = string` _# Same number on both sides_
```
>>> a, d
('S', 'M')
```
`>>> a, b, c = string` _# Error if not_
```
...error text omitted...
ValueError: too ma... |
There are a variety of ways to employ slicing to make
this last case work:
`>>> a, b, c = string[0], string[1], string[2:]` _# Index and slice_
```
>>> a, b, c
('S', 'P', 'AM')
```
`>>> a, b, c = list(string[:2]) + [string[2:]]` _# Slice and concatenate_
```
>>> a, b, c
```
**|**
-----
```
('S', 'P', 'AM'... |
In this
case, we are assigning a tuple of two items, where the first item is a nested sequence (a
string), exactly as though we had coded it this way:
`>>> ((a, b), c) = ('SP', 'AM')` _# Paired by shape and position_
```
>>> a, b, c
('S', 'P', 'AM')
```
Python pairs the first string on the right ('SP') with the f... |
In this event, the sequence-nesting shape of the object on the
left must match that of the object on the right. |
Nested sequence assignment like this is
somewhat advanced, and rare to see, but it can be convenient for picking out the parts
of data structures with known shapes.
For example, we’ll see in Chapter 13 that this technique also works in for loops, because
loop items are assigned to the target given in the loop header:
... |
# Simple tuple assignment
for ((a, b), c) in [((1, 2), 3), ((4, 5), 6)]: ... |
# Nested tuple assignment
```
In a note in Chapter 18, we’ll also see that this nested tuple (really, sequence) unpacking
assignment form works for function argument lists in Python 2.6 (though not in 3.0),
because function arguments are passed by assignment as well:
```
def f(((a, b), c)): # For arguments too... |
To
make sense of this, you need to know that the range built-in function generates a list
of successive integers:
**|**
-----
`>>> range(3)` _# Use list(range(3)) in Python 3.0_
```
[0, 1, 2]
```
Because range is commonly used in for loops, we’ll say more about it in Chapter 13.
Another place you may see a tupl... |
front, L = L[0], L[1:]` _# See next section for 3.0 alternative_
```
... |
print(front, L)
...
1 [2, 3, 4]
2 [3, 4]
3 [4]
4 []
```
The tuple assignment in the loop here could be coded as the following two lines instead,
but it’s often more convenient to string them together:
```
... |
front = L[0]
... |
L = L[1:]
```
Notice that this code is using the list as a sort of stack data structure, which can often
also be achieved with the `append and` `pop methods of list objects; here,` `front =`
```
L.pop(0) would have much the same effect as the tuple assignment statement, but it
```
would be an in-place change. |
We’ll learn more about `while loops, and other (often`
better) ways to step through a sequence with for loops, in Chapter 13.
###### Extended Sequence Unpacking in Python 3.0
The prior section demonstrated how to use manual slicing to make sequence assignments more general. |
In Python 3.0 (but not 2.6), sequence assignment has been generalized to make this easier. |
In short, a single _starred name,_ `*X, can be used in the`
assignment target in order to specify a more general matching against the sequence—
the starred name is assigned a list, which collects all items in the sequence not assigned
to other names. |
This is especially handy for common coding patterns such as splitting
a sequence into its “front” and “rest”, as in the preceding section’s last example.
###### Extended unpacking in action
Let’s look at an example. |
As we’ve seen, sequence assignments normally require exactly
as many names in the target on the left as there are items in the subject on the right.
We get an error if the lengths disagree (unless we manually sliced on the right, as shown
in the prior section):
```
C:\misc> c:\python30\python
>>> seq = [1, 2, 3, 4]... |
In the following continuation of our interactive session, a matches the first
item in the sequence, and b matches the rest:
```
>>> a, *b = seq
>>> a
1
>>> b
[2, 3, 4]
```
When a starred name is used, the number of items in the target on the left need not
match the length of the subject sequence. |
In fact, the starred name can appear anywhere
in the target. |
For instance, in the next interaction b matches the last item in the sequence, and a matches everything before the last:
```
>>> *a, b = seq
>>> a
[1, 2, 3]
>>> b
4
```
When the starred name appears in the middle, it collects everything between the other
names listed. |
Thus, in the following interaction a and c are assigned the first and last
items, and b gets everything in between them:
```
>>> a, *b, c = seq
>>> a
1
>>> b
[2, 3]
>>> c
4
```
More generally, wherever the starred name shows up, it will be assigned a list that
collects every unassigned name at that posit... |
Here it is unpacking characters in a string:
```
>>> a, *b = 'spam'
>>> a, b
('s', ['p', 'a', 'm'])
>>> a, *b, c = 'spam'
```
**|**
-----
```
>>> a, b, c
('s', ['p', 'a'], 'm')
```
This is similar in spirit to slicing, but not exactly the same—a sequence unpacking
assignment always returns a list for m... |
front, *L = L` _# Get first, rest without slicing_
```
... |
print(front, L)
...
1 [2, 3, 4]
2 [3, 4]
3 [4]
4 []
###### Boundary cases
```
Although extended sequence unpacking is flexible, some boundary cases are worth
noting. |
First, the starred name may match just a single item, but is always assigned a list:
```
>>> seq
[1, 2, 3, 4]
>>> a, b, c, *d = seq
>>> print(a, b, c, d)
1 2 3 [4]
```
Second, if there is nothing left to match the starred name, it is assigned an empty list,
regardless of where it appears. |
In the following, a, b, c, and d have matched every item
in the sequence, but Python assigns e an empty list instead of treating this as an error
case:
```
>>> a, b, c, d, *e = seq
>>> print(a, b, c, d, e)
1 2 3 4 []
>>> a, b, *e, c, d = seq
>>> print(a, b, c, d, e)
1 2 3 4 []
```
**|**
-----
Finally, e... |
We
can usually achieve the same effects with explicit indexing and slicing (and in fact must
in Python 2.X), but extended unpacking is simpler to code. |
The common “first, rest”
splitting coding pattern, for example, can be coded either way, but slicing involves extra
work:
```
>>> seq
[1, 2, 3, 4]
```
`>>> a, *b = seq` _# First, rest_
```
>>> a, b
(1, [2, 3, 4])
```
`>>> a, b = seq[0], seq[1:]` _# First, rest: traditional_
```
>>> a, b
(1, [2, 3, 4])
``... |
We met the for loop iteration tool briefly
in Part II and will study it formally in Chapter 13. |
In Python 3.0, extended assignments
may show up after the word for, where a simple variable name is more commonly used:
```
for (a, *b, c) in [(1, 2, 3, 4), (5, 6, 7, 8)]:
...
```
When used in this context, on each iteration Python simply assigns the next tuple of
values to the tuple of names. |
On the first loop, for example, it’s as if we’d run the
following assignment statement:
```
a, *b, c = (1, 2, 3, 4) # b gets [2, 3]
```
The names a, b, and c can be used within the loop’s code to reference the extracted
components. |
In fact, this is really not a special case at all, but just an instance of general
assignment at work. |
As we saw earlier in this chapter, we can do the same thing with
simple tuple assignment in both Python 2.X and 3.X:
```
for (a, b, c) in [(1, 2, 3), (4, 5, 6)]: # a, b, c = (1, 2, 3), ...
```
And we can always emulate 3.0’s extended assignment behavior in 2.6 by manually
slicing:
```
for all in [(1, 2, 3, 4)... |
The following, for example, assigns the three variables a, b, and c to
the string 'spam':
```
>>> a = b = c = 'spam'
>>> a, b, c
('spam', 'spam', 'spam')
```
This form is equivalent to (but easier to code than) these three assignments:
```
>>> c = 'spam'
>>> b = c
>>> a = b
###### Multiple-target assignme... |
This behavior is fine for immutable
types—for example, when initializing a set of counters to zero (recall that variables
**|**
-----
must be assigned before they can be used in Python, so you must initialize counters to
zero before you can start adding to them):
```
>>> a = b = 0
>>> b = b + 1
>>> a, b
(0,... |
As
long as the object assigned is immutable, it’s irrelevant if more than one name references
it.
As usual, though, we have to be more cautious when initializing variables to an empty
mutable object such as a list or dictionary:
```
>>> a = b = []
>>> b.append(42)
>>> a, b
([42], [42])
```
This time, because ... |
This is really just another example of the
```
shared reference phenomenon we first met in Chapter 6. |
To avoid the issue, initialize
mutable objects in separate statements instead, so that each creates a distinct empty
object by running a distinct literal expression:
```
>>> a = []
>>> b = []
>>> b.append(42)
>>> a, b
([], [42])
###### Augmented Assignments
```
Beginning with Python 2.0, the set of addition... |
Known as augmented assignments, and borrowed from
the C language, these formats are mostly just shorthand. They imply the combination
of a binary expression and an assignment. |
For instance, the following two formats are
now roughly equivalent:
```
X = X + Y # Traditional form
X += Y # Newer augmented form
```
_Table 11-2. |
Augmented assignment statements_
```
X += Y X &= Y X -= Y X |= Y
X *= Y X ^= Y X /= Y X >>= Y
X %= Y X <<= Y X **= Y X //= Y
```
Augmented assignment works on any type that supports the implied binary expression.
For example, here are two ways to add 1 to a name:
**|**
-----
```
>>> x = 1
```
`>>> x = x + 1`... |
Thus,
the second line here is equivalent to typing the longer S = S + "SPAM":
```
>>> S = "spam"
```
`>>> S += "SPAM"` _# Implied concatenation_
```
>>> S
'spamSPAM'
```
As shown in Table 11-2, there are analogous augmented assignment forms for every
Python binary expression operator (i.e., each operator with v... |
For instance, X *= Y multiplies and assigns, X >>= Y shifts right and assigns, and
so on. |
X //= Y (for floor division) was added in version 2.2.
Augmented assignments have three advantages:[*]
- There’s less for you to type. |
Need I say more?
- The left side only has to be evaluated once. In X += Y, X may be a complicated object
expression. In the augmented form, it only has to be evaluated once. |
However, in
the long form, X = X + Y, X appears twice and must be run twice. Because of this,
augmented assignments usually run faster.
- The optimal technique is automatically chosen. |
That is, for objects that support
in-place changes, the augmented forms automatically perform in-place change operations instead of slower copies.
The last point here requires a bit more explanation. |
For augmented assignments, inplace operations may be applied for mutable objects as an optimization. Recall that
lists can be extended in a variety of ways. |
To add a single item to the end of a list, we
can concatenate or call append:
```
>>> L = [1, 2]
```
`>>> L = L + [3]` _# Concatenate: slower_
```
>>> L
[1, 2, 3]
```
`>>> L.append(4)` _# Faster, but in-place_
```
>>> L
[1, 2, 3, 4]
```
- C/C++ programmers take note: although Python now supports statements... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.