Python Statements in Simple Terms, Statements Are The Things You Write To Tell Python What Your Programs Should Do
Python Statements in Simple Terms, Statements Are The Things You Write To Tell Python What Your Programs Should Do
In simple terms, statements are the things you write to tell Python what your programs
should do.
if x > y:
x=1
y=2
The syntax rule is only that for a given single nested block, all of its statements must be indented
the same distance to the right.
the body of
a compound statement can instead appear on the same line as the header in Python,
after the colon:
if x > y: print(x)
Enter text:spam
SPAM
Enter text:42
42
Enter text:stop
Enter text:2
4
Enter text:40
1600
Enter text:stop
Bye
Enter text:5
25
Enter text:xyz
Bad!Bad!Bad!Bad!Bad!Bad!Bad!Bad!
Enter text:10
100
Enter text:stop
Enter text:50
2500.0
Enter text:40.5
1640.25
Enter text:1.23E-100
1.5129e-200
Enter text:spam
Bad!Bad!Bad!Bad!Bad!Bad!Bad!Bad!
Enter text:stop
Bye
Nesting Code Three Levels Deep
while True:
reply = input('Enter text:')
if reply == 'stop':
break
elif not reply.isdigit():
print('Bad!' * 8)
else:
num = int(reply)
if num < 20:
print('low')
else:
print(num ** 2)
print('Bye')
Enter text:19
low
Enter text:20
400
Enter text:spam
Bad!Bad!Bad!Bad!Bad!Bad!Bad!Bad!
Enter text:stop
Bye
Assignment Statements
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
Sequence Assignments
% python
>>> nudge = 1 # Basic assignment
>>> 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)
>>> nudge = 1
>>> wink = 2
>>> nudge, wink = wink, nudge # Tuples: swaps values
>>> nudge, wink # Like T = nudge; nudge = wink; wink = T
(2, 1)
for (a, b, c) in [(1, 2, 3), (4, 5, 6)]: ... # Simple tuple assignment
for ((a, b), c) in [((1, 2), 3), ((4, 5), 6)]: ... # Nested tuple assignment
>>> L = [1, 2, 3, 4]
>>> while L:
... front, L = L[0], L[1:] # See next section for 3.X * alternative
... print(front, L)
...
1 [2, 3, 4]
2 [3, 4]
3 [4]
4 []
front = L[0]
... L = L[1:]
Notice that this code is using the list as a sort of stack data structure
>>> a, *b = seq
>>> a
1
>>> b
[2, 3, 4]
>>> a, b, *c = seq
>>> a
Assignment Statements | 345
1
>>> b
2
>>> c
[3, 4]
works for any sequence types (really, again, any iterable), not just lists. Here it is unpacking
characters in a string and a range (an iterable in 3.X):
>>> a, *b = 'spam'
>>> a, b
('s', ['p', 'a', 'm'])
>>> a, *b, c = 'spam'
>>> a, b, c
('s', ['p', 'a'], 'm')
>>> a, *b, c = range(4)
>>> a, b, c
(0, [1, 2], 3)
This is similar in spirit to slicing, but not exactly the same—a sequence unpacking
assignment always returns a list for multiple matched items, whereas slicing returns a
sequence of the same type as the object sliced:
>>> S = 'spam'
>>> S[0], S[1:] # Slices are type-specific, * assignment always returns a list
('s', 'pam')
>>> S[0], S[1:3], S[3]
('s', 'pa', 'm')
Given this extension in 3.X, as long as we’re processing a list the last example of the
prior section becomes even simpler, since we don’t have to manually slice to get the
first and rest of the items:
>>> L = [1, 2, 3, 4]
>>> while L:
... front, *L = L # Get first, rest without slicing
... print(front, L)
...
1 [2, 3, 4]
2 [3, 4]
3 [4]
4 []
Boundary cases
>>> seq = [1, 2, 3, 4]
346 | Chapter 11: Assignments, Expressions, and Prints
>>> a, b, c, *d = seq
>>> print(a, b, c, d)
1 2 3 [4]
>>> 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 []
>>> 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])
Multiple-Target Assignments
>>> 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 assignment and shared references
>>> a = b = 0
>>> b = b + 1
>>> a, b
(0, 1)
>>> a = b = []
>>> b.append(42)
>>> a, b
([42], [42])(shared reference)
>>> a = []
>>> b = [] # a and b do not share the same object
>>> b.append(42)
>>> a, b
([], [42])
Augmented Assignments
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
>>> x = 1
>>> x = x + 1 # Traditional
>>> x
2
>>> x += 1 # Augmented
>>> x
3
When applied to a sequence such as a string, the augmented form performs concatenation
instead. Thus, the second line here is equivalent to typing the longer S = S +
"SPAM":
>>> S = "spam"
>>> S += "SPAM" # Implied concatenation
>>> S
'spamSPAM'
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]
And to add a set of items to the end, we can either concatenate again or call the list
extend method:2
>>> L = L + [5, 6] # Concatenate: slower
>>> L
[1, 2, 3, 4, 5, 6]
>>> L.extend([7, 8]) # Faster, but in place
>>> L
[1, 2, 3, 4, 5, 6, 7, 8]
>>> L
['s', 'p', 'a', 'm']
>>> L = L + 'spam'
TypeError: can only concatenate list (not "str") to list
Expression Statements
Expressions are commonly
used as statements in two situations:
For calls to functions and methods
Some functions and methods do their work without returning a value. Such functions
are sometimes called procedures in other languages. Because they don’t return
values that you might be interested in retaining, you can call these functions with
expression statements.
For printing values at the interactive prompt
Python echoes back the results of expressions typed at the interactive command
line. Technically, these are expression statements, too; they serve as a shorthand
for typing print statements.
Operation Interpretation
spam(eggs, ham) Function calls
spam.ham(eggs) Method calls
spam Printing variables in the interactive interpreter
print(a, b, c, sep='') Printing operations in Python 3.X
yield x ** 2 Yielding expression statements
Print Operations
File object methods
file.write(str)).