Text stringlengths 1 9.41k |
|---|
Because this crops up fairly often, a print extension is available to make it unnecessary.
In 3.0, the file keyword allows a single print call to send its text to a file’s write method,
without actually resetting `sys.stdout. |
Because the redirection is temporary, normal`
```
print calls keep printing to the original output stream. |
In 2.6, a print statement that
```
begins with a >> followed by an output file object (or other compatible object) has the
same effect. |
For example, the following again sends printed text to a file named log.txt:
```
log = open('log.txt', 'a') # 3.0
print(x, y, z, file=log) # Print to a file-like object
print(a, b, c) # Print to original stdout
log = open('log.txt', 'a') # 2.6
print >> log, x, y, z # Pr... |
If you use these forms, however, be sure
#In both 2.6 and 3.0 you may also be able to use the __stdout__ attribute in the sys module, which refers to
the original value `sys.stdout had at program startup time. |
You still need to restore` `sys.stdout to`
```
sys.__stdout__ to go back to this original stream value, though. |
See the sys module documentation for more
```
details.
**|**
-----
to give them a file object (or an object that has the same write method as a file object),
not a file’s name string. |
Here is the technique in action:
```
C:\misc> c:\python30\python
>>> log = open('log.txt', 'w')
```
`>>> print(1, 2, 3, file=log)` _# 2.6: print >> log, 1, 2, 3_
```
>>> print(4, 5, 6, file=log)
>>> log.close()
```
`>>> print(7, 8, 9)` _# 2.6: print 7, 8, 9_
```
7 8 9
>>> print(open('log.txt').read())
1... |
You can either use its file write methods and format the output manually,
```
or print with redirection syntax:
```
>>> import sys
>>> sys.stderr.write(('Bad!' * 8) + '\n')
Bad!Bad!Bad!Bad!Bad!Bad!Bad!Bad!
```
`>>> print('Bad!' * 8, file=sys.stderr)` _# 2.6: print >> sys.stderr, 'Bad' * 8_
```
Bad!Bad!Bad!Bad... |
The following interaction prints both ways
in 3.0, then redirects the output to an external file to verify that the same text is printed:
```
>>> X = 1; Y = 2
```
`>>> print(X, Y)` _# Print: the easy way_
```
1 2
```
`>>> import sys` _# Print: the hard way_
```
>>> sys.stdout.write(str(X) + ' ' + str(Y) + '\n')... |
For another example of the equivalence between prints and
file writes, watch for a 3.0 print function emulation example in Chapter 18; it uses this
code pattern to provide a general 3.0 print function equivalent for use in Python 2.6.
**|**
-----
###### Version-Neutral Printing
Finally, if you cannot restrict your... |
For one, you can code 2.6 print statements and let 3.0’s 2to3 conversion script translate them to 3.0 function calls automatically. |
See the Python 3.0 documentation for more details about this script; it
attempts to translate 2.X code to run under 3.0.
Alternatively, you can code 3.0 print function calls in your 2.6 code, by enabling the
function call variant with a statement like the following:
```
from __future__ import print_function
```
Thi... |
This way, you can
use 3.0 print features and won’t have to change your prints if you later migrate to 3.0.
Also keep in mind that simple prints, like those in the first row of Table 11-5, work in
_either version of Python—because any expression may be enclosed in parentheses, we_
can always pretend to be calling a 3.0... |
In 3.0, for example, any number of objects may be listed in the call’s parentheses:
```
C:\misc> c:\python30\python
```
`>>> print('spam')` _# 3.0 print function call syntax_
```
spam
```
`>>> print('spam', 'ham', 'eggs')` _# These are mutiple argments_
```
spam ham eggs
```
The first of these works the same i... |
I’ll usually
warn you that the results may have extra enclosing parentheses in 2.6
because multiple items are a tuple, but I sometimes don’t, so please
consider this note a blanket warning—if you see extra parentheses in
your printed text in 2.6, either drop the parentheses in your print statements, recode your prints ... |
Although these are generally simple to use,
they have some alternative forms that, while optional, are often convenient in practice:
augmented assignment statements and the redirection form of print operations, for
example, allow us to avoid some manual coding work. |
Along the way, we also studied
the syntax of variable names, stream redirection techniques, and a variety of common
mistakes to avoid, such as assigning the result of an `append method call back to a`
variable.
In the next chapter, we’ll continue our statement tour by filling in details about the
```
if statement, Pyt... |
Before we move
on, though, the end-of-chapter quiz will test your knowledge of what you’ve learned
here.
###### Test Your Knowledge: Quiz
1. |
Name three ways that you can assign three variables to the same value.
2. Why might you need to care when assigning three variables to a mutable object?
3. What’s wrong with saying L = L.sort()?
4. |
How might you use the print operation to send text to an external file?
###### Test Your Knowledge: Answers
1. |
You can use multiple-target assignments (A = B = C = 0), sequence assignment
(A, B, C = 0, 0, 0), or multiple assignment statements on three separate lines
(A = 0, B = 0, and C = 0). |
With the latter technique, as introduced in Chapter 10,
you can also string the three separate statements together on the same line by
separating them with semicolons (A = 0; B = 0; C = 0).
**|**
-----
2. |
If you assign them this way:
```
A = B = C = []
```
all three names reference the same object, so changing it in-place from one (e.g.,
```
A.append(99)) will affect the others. |
This is true only for in-place changes to mu
```
table objects like lists and dictionaries; for immutable objects such as numbers and
strings, this issue is irrelevant.
3. |
The list sort method is like append in that it makes an in-place change to the subject
list—it returns `None, not the list it changes. |
The assignment back to` `L sets` `L to`
```
None, not to the sorted list. |
As we’ll see later in this part of the book, a newer built
```
in function, sorted, sorts any sequence and returns a new list with the sorting result;
because this is not an in-place change, its result can be meaningfully assigned to a
name.
4. |
To print to a file for a single print operation, you can use 3.0’s print(X, file=F)
call form, use 2.6’s extended `print >> file, X statement form, or assign`
```
sys.stdout to a manually opened file before the print and restore the original after.
```
You can also redirect all of a program’s printed text to a file w... |
Because this is our first in-depth
look at compound statements—statements that embed other statements—we will also
explore the general concepts behind the Python statement syntax model here in more
detail than we did in the introduction in Chapter 10. |
Because the if statement introduces the notion of tests, this chapter will also deal with Boolean expressions and fill
in some details on truth tests in general.
###### if Statements
In simple terms, the Python if statement selects actions to perform. |
It’s the primary
selection tool in Python and represents much of the logic a Python program possesses.
It’s also our first compound statement. |
Like all compound Python statements, the if
statement may contain other statements, including other ifs. |
In fact, Python lets you
combine statements in a program sequentially (so that they execute one after another),
and in an arbitrarily nested fashion (so that they execute only under certain conditions).
###### General Format
The Python if statement is typical of if statements in most procedural languages. |
It
takes the form of an if test, followed by one or more optional elif (“else if”) tests and
a final optional else block. |
The tests and the else part each have an associated block
of nested statements, indented under a header line. |
When the if statement runs, Python
executes the block of code associated with the first test that evaluates to true, or the
```
else block if all tests prove false. |
The general form of an if statement looks like this:
if <test1>: # if test
<statements1> # Associated block
elif <test2>: # Optional elifs
<statements2>
else: # Optional else
<statements3>
```
-----
###### Basic Examples
To demonstrate, let’s look at a few simple example... |
All
parts are optional, except the initial if test and its associated statements. Thus, in the
simplest case, the other parts are omitted:
```
>>> if 1:
... |
print('true')
...
true
```
Notice how the prompt changes to ... |
for continuation lines when typing interactively
in the basic interface used here; in IDLE, you’ll simply drop down to an indented line
instead (hit Backspace to back up). |
A blank line (which you can get by pressing Enter
twice) terminates and runs the entire statement. Remember that 1 is Boolean true, so
this statement’s test always succeeds. |
To handle a false result, code the else:
```
>>> if not 1:
... print('true')
... else:
... |
print('false')
...
false
###### Multiway Branching
```
Now here’s an example of a more complex `if statement, with all its optional parts`
present:
```
>>> x = 'killer rabbit'
>>> if x == 'roger':
... |
print("how's jessica?")
... elif x == 'bugs':
... print("what's up doc?")
... else:
... print('Run away! Run away!')
...
Run away! |
Run away!
```
This multiline statement extends from the if line through the else block. |
When it’s
run, Python executes the statements nested under the first test that is true, or the
```
else part if all tests are false (in this example, they are). |
In practice, both the elif and
else parts may be omitted, and there may be more than one statement nested in each
```
section. |
Note that the words if, elif, and else are associated by the fact that they line
up vertically, with the same indentation.
If you’ve used languages like C or Pascal, you might be interested to know that there
is no switch or case statement in Python that selects an action based on a variable’s
value. |
Instead, multiway branching is coded either as a series of if/elif tests, as in the
prior example, or by indexing dictionaries or searching lists. |
Because dictionaries and
lists can be built at runtime, they’re sometimes more flexible than hardcoded if logic:
**|** **f**
-----
```
>>> choice = 'ham'
```
`>>> print({'spam': 1.25,` _# A dictionary-based 'switch'_
`... |
'ham': 1.99,` _# Use has_key or get for default_
```
... 'eggs': 0.99,
... |
'bacon': 1.10}[choice])
1.99
```
Although it may take a few moments for this to sink in the first time you see it, this
dictionary is a multiway branch—indexing on the key choice branches to one of a set
of values, much like a switch in C. |
An almost equivalent but more verbose Python if
statement might look like this:
```
>>> if choice == 'spam':
... print(1.25)
... elif choice == 'ham':
... print(1.99)
... |
elif choice == 'eggs':
... print(0.99)
... elif choice == 'bacon':
... print(1.10)
... else:
... |
print('Bad choice')
...
1.99
```
Notice the else clause on the if here to handle the default case when no key matches.
As we saw in Chapter 8, dictionary defaults can be coded with `in expressions,` `get`
method calls, or exception catching. |
All of the same techniques can be used here to
code a default action in a dictionary-based multiway branch. Here’s the get scheme at
work with defaults:
```
>>> branch = {'spam': 1.25,
... |
'ham': 1.99,
... |
'eggs': 0.99}
>>> print(branch.get('spam', 'Bad choice'))
1.25
>>> print(branch.get('bacon', 'Bad choice'))
Bad choice
```
An in membership test in an if statement can have the same default effect:
```
>>> choice = 'bacon'
>>> if choice in branch:
... |
print(branch[choice])
... else:
... |
print('Bad choice')
...
Bad choice
```
Dictionaries are good for associating values with keys, but what about the more complicated actions you can code in the statement blocks associated with if statements?
In Part IV, you’ll learn that dictionaries can also contain functions to represent more
complex branch actio... |
Such functions appear as
**f** **|**
-----
dictionary values, may be coded as function names or lambdas, and are called by adding
parentheses to trigger their actions; stay tuned for more on this topic in Chapter 19.
Although dictionary-based multiway branching is useful in programs that deal with
more dynamic dat... |
As a rule of thumb in
coding, when in doubt, err on the side of simplicity and readability; it’s the “Pythonic”
way.
###### Python Syntax Rules
I introduced Python’s syntax model in Chapter 10. |
Now that we’re stepping up to larger
statements like the if, this section reviews and expands on the syntax ideas introduced
earlier. In general, Python has a simple, statement-based syntax. |
However, there are a
few properties you need to know about:
- Statements execute one after another, until you say otherwise. |
Python normally runs statements in a file or nested block in order from first to last, but statements like if (and, as you’ll see, loops) cause the interpreter to jump around in
your code. |
Because Python’s path through a program is called the control flow,
statements such as if that affect it are often called control-flow statements.
- Block and statement boundaries are detected automatically. |
As we’ve seen,
there are no braces or “begin/end” delimiters around blocks of code in Python;
instead, Python uses the indentation of statements under a header to group the
statements in a nested block. |
Similarly, Python statements are not normally terminated with semicolons; rather, the end of a line usually marks the end of the
statement coded on that line.
- Compound statements = header + “:” + indented statements. |
All compound
statements in Python follow the same pattern: a header line terminated with a
colon, followed by one or more nested statements, usually indented under the
header. |
The indented statements are called a block (or sometimes, a suite). |
In the
```
if statement, the elif and else clauses are part of the if, but they are also header
```
lines with nested blocks of their own.
- Blank lines, spaces, and comments are usually ignored. |
Blank lines are ignored
in files (but not at the interactive prompt, when they terminate compound statements). |
Spaces inside statements and expressions are almost always ignored
(except in string literals, and when used for indentation). |
Comments are always
ignored: they start with a # character (not inside a string literal) and extend to the
end of the current line.
- Docstrings are ignored but are saved and displayed by tools. |
Python supports
an additional comment form called documentation strings (docstrings for short),
which, unlike # comments, are retained at runtime for inspection. |
Docstrings are
simply strings that show up at the top of program files and some statements. |
Python
**|** **f**
-----
ignores their contents, but they are automatically attached to objects at runtime
and may be displayed with documentation tools. |
Docstrings are part of Python’s
larger documentation strategy and are covered in the last chapter in this part of the
book.
As you’ve seen, there are no variable type declarations in Python; this fact alone makes
for a much simpler language syntax than what you may be used to. |
However, for most
new users the lack of the braces and semicolons used to mark blocks and statements
in many other languages seems to be the most novel syntactic feature of Python, so let’s
explore what this means in more detail.
###### Block Delimiters: Indentation Rules
Python detects block boundaries automatically... |
All statements indented the same distance to the right
belong to the same block of code. In other words, the statements within a block line
up vertically, as in a column. |
The block ends when the end of the file or a lesser-indented
line is encountered, and more deeply nested blocks are simply indented further to the
right than the statements in the enclosing block.
For instance, Figure 12-1 demonstrates the block structure of the following code:
```
x = 1
if x:
y = 2
if y:
... |
Nested blocks of code: a nested block starts with a statement indented further to the right_
_and ends with either a statement that is indented less, or the end of the file._
**|**
-----
This code contains three blocks: the first (the top-level code of the file) is not indented
at all, the second (within the outer ... |
Nested blocks can start
in any column; indentation may consist of any number of spaces and tabs, as long as
it’s the same for all the statements in a given single block. |
That is, Python doesn’t care
_how you indent your code; it only cares that it’s done consistently. |
Four spaces or one_
tab per indentation level are common conventions, but there is no absolute standard
in the Python world.
Indenting code is quite natural in practice. |
For example, the following (arguably silly)
code snippet demonstrates common indentation errors in Python code:
```
x = 'SPAM' # Error: first line indented
if 'rubbery' in 'shrubbery':
print(x * 8)
x += 'NI' # Error: unexpected indentation
if x.endswith('NI'):
x *= 2
... |
However, indentation is really part of Python syntax, not just a
stylistic suggestion: all the statements within any given single block must be indented
to the same level, or Python reports a syntax error. |
This is intentional—because you
don’t need to explicitly mark the start and end of a nested block of code, some of the
syntactic clutter found in other languages is unnecessary in Python.
As described in Chapter 10, making indentation part of the syntax model also enforces
consistency, a crucial component of readabili... |
Python’s syntax is sometimes described as “what you see is what you
get”—the indentation of each line of code unambiguously tells readers what it is associated with. |
This uniform and consistent appearance makes Python code easier to
maintain and reuse.
**|** **f**
-----
Indentation is more natural than the details might imply, and it makes your code reflect
its logical structure. |
Consistently indented code always satisfies Python’s rules.
Moreover, most text editors (including IDLE) make it easy to follow Python’s indentation model by automatically indenting code as you type it.
###### Avoid mixing tabs and spaces: New error checking in 3.0
One rule of thumb: although you can use spaces or ta... |
Technically, tabs count
for enough spaces to move the current column number up to a multiple of 8, and your
code will work if you mix tabs and spaces consistently. |
However, such code can be
difficult to change. |
Worse, mixing tabs and spaces makes your code difficult to read—
tabs may look very different in the next programmer’s editor than they do in yours.
In fact, Python 3.0 now issues an error, for these very reasons, when a script mixes tabs
and spaces for indentation inconsistently within a block (that is, in a way that... |
Python 2.6 allows such scripts to run, but
it has a -t command-line flag that will warn you about inconsistent tab usage and a
```
-tt flag that will issue errors for such code (you can use these switches in a command
```
line like python –t main.py in a system shell window). |
Python 3.0’s error case is equivalent to 2.6’s -tt switch.
###### Statement Delimiters: Lines and Continuations
A statement in Python normally ends at the end of the line on which it appears. |
When
a statement is too long to fit on a single line, though, a few special rules may be used
to make it span multiple lines:
- Statements may span multiple lines if you’re continuing an open syntactic
**pair. |
Python lets you continue typing a statement on the next line if you’re coding**
something enclosed in a (), {}, or [] pair. |
For instance, expressions in parentheses
and dictionary and list literals can span any number of lines; your statement doesn’t
end until the Python interpreter reaches the line on which you type the closing part
of the pair (a ), }, or ]). |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.