0% found this document useful (0 votes)
38 views

Python Statements in Simple Terms, Statements Are The Things You Write To Tell Python What Your Programs Should Do

Python uses statements to tell the interpreter what programs should do. Statements follow certain syntax rules, like using a colon after header lines in compound statements. Key syntax differences from other languages include optional parentheses and semicolons, and using indentation to group blocks of code. The document then demonstrates various Python statement types like assignments, augmented assignments, sequence unpacking, and interactive loops, showing how user input can be handled, errors tested for, and results displayed.

Uploaded by

kavirajee
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
38 views

Python Statements in Simple Terms, Statements Are The Things You Write To Tell Python What Your Programs Should Do

Python uses statements to tell the interpreter what programs should do. Statements follow certain syntax rules, like using a colon after header lines in compound statements. Key syntax differences from other languages include optional parentheses and semicolons, and using indentation to group blocks of code. The document then demonstrates various Python statement types like assignments, augmented assignments, sequence unpacking, and interactive loops, showing how user input can be handled, errors tested for, and results displayed.

Uploaded by

kavirajee
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 11

Python Statements

In simple terms, statements are the things you write to tell Python what your programs
should do.
if x > y:
x=1
y=2

What Python Adds


The one new syntax component in Python is the colon character (:). All Python compound
statements—statements that have other statements nested inside them—follow
the same general pattern of a header line terminated in a colon, followed by a nested
block of code usually indented underneath the header line, like this:
Header line:
Nested statement block
The colon is required, and omitting it is probably the most common coding mistake
among new Python programmers

What Python Removes


Parentheses are optional
End-of-line is end of statement
You don’t need to terminate statements with semicolons in Python

End of indentation is end of block


in Python, we consistently indent all the statements in a given single nested
block the same distance to the right, and Python uses the statements’ physical indentation
to determine where the block starts and stops:
if x > y:
x=1
y=2
By indentation, I mean the blank whitespace all the way to the left of the two nested
statements here.

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.

A Few Special Cases


a = 1; b = 2; print(a + b) # Three statements on one line

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)

A Simple Interactive Loop


while True:
reply = input('Enter text:')
if reply == 'stop': break
print(reply.upper())

Enter text:spam
SPAM
Enter text:42
42
Enter text:stop

Doing Math on User Inputs


while True:
reply = input('Enter text:')
if reply == 'stop': break
print(int(reply) ** 2)
print('Bye')

Enter text:2
4
Enter text:40
1600
Enter text:stop
Bye

Handling Errors by Testing Inputs


while True:
reply = input('Enter text:')
if reply == 'stop':
break
elif not reply.isdigit():
print('Bad!' * 8)
else:
print(int(reply) ** 2)
print('Bye')

Enter text:5
25
Enter text:xyz
Bad!Bad!Bad!Bad!Bad!Bad!Bad!Bad!
Enter text:10
100
Enter text:stop

Handling Errors with try Statements


while True:
reply = input('Enter text:')
if reply == 'stop': break
try:
num = int(reply)
except:
print('Bad!' * 8)
else:
print(num ** 2)
print('Bye')

Supporting floating-point numbers


while True:
reply = input('Enter text:')
if reply == 'stop': break
try:
print(float(reply) ** 2)
except:
print('Bad!' * 8)
print('Bye')

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

a few properties to keep in mind:

Assignments create object references

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.

Names must be assigned before being referenced.

Some operations perform assignments implicitly.

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 3.X)
spam = ham = 'lunch' Multiple-target assignment
spams += 42 Augmented assignment (equivalent to spams = spams + 42)

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)

>>> [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
('A', 'C')

Advanced sequence assignment patterns


>>> 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 many values to unpack (expected 3)

>>> 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')
>>> a, b = string[:2] # Same, but simpler
>>> c = string[2:]
>>> a, b, c
('S', 'P', 'AM')
>>> (a, b), c = string[:2], string[2:] # Nested sequences
>>> a, b, c
('S', 'P', 'AM')

>>> ((a, b), c) = ('SP', 'AM') # Paired by shape and position


>>> a, b, c
('S', 'P', 'AM')

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

>>> red, green, blue = range(3)


>>> red, blue
(0, 2)

>>> list(range(3)) # list() required in Python 3.X only


[0, 1, 2]

>>> 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

Extended Sequence Unpacking in Python 3.X(* position)


C:\code> c:\python33\python
>>> seq = [1, 2, 3, 4]
>>> a, b, c, d = seq
>>> print(a, b, c, d)
1234
>>> a, b = seq
ValueError: too many values to unpack (expected 2)

>>> *a, b = seq


>>> a
[1, 2, 3]
>>> b
4

>>> a, *b = seq
>>> a
1
>>> b
[2, 3, 4]

>>> a, *b, c = seq


>>> a
1
>>> b
[2, 3]
>>> c
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 []

>>> a, *b, c, *d = seq


SyntaxError: two starred expressions in assignment
>>> a, b = seq
ValueError: too many values to unpack (expected 2)
>>> *a = seq
SyntaxError: starred assignment target must be in a list or tuple
>>> *a, = seq
>>> a
[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])

>>> *a, b = seq # Rest, last


>>> a, b
([1, 2, 3], 4)
>>> a, b = seq[:-1], seq[-1] # Rest, last: traditional
>>> a, b
([1, 2, 3], 4)

Application to for loops


for (a, *b, c) in [(1, 2, 3, 4), (5, 6, 7, 8)]:
...

for (a, b, c) in [(1, 2, 3), (4, 5, 6)]: # a, b, c = (1, 2, 3), ...

for all in [(1, 2, 3, 4), (5, 6, 7, 8)]:


a, b, c = all[0], all[1:3], all[3]

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])

>>> a, b = [], [] # a and b do not share the same object

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'

Augmented assignments have three advantages: 1


• There’s less for you to type. Need I say more?
• The left side has to be evaluated only once. In X += Y, X may be a complicated object
expression. In the augmented form, its code must be run only 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]
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 += [9, 10] # Mapped to L.extend([9, 10])


>>> L
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Note however, that because of this equivalence += for a list is not exactly the same as a
+ and = in all cases—for lists += allows arbitrary sequences (just like extend), but concatenation
normally does not:
>>> L = []
>>> L += 'spam'

>>> L
['s', 'p', 'a', 'm']
>>> L = L + 'spam'
TypeError: can only concatenate list (not "str") to list

Augmented assignment and shared references


>>> L = [1, 2]
>>> M = L # L and M reference the same object
>>> L = L + [3, 4] # Concatenation makes a new object
>>> L, M # Changes L but not M
([1, 2, 3, 4], [1, 2])
>>> L = [1, 2]
>>> M = L
>>> L += [3, 4] # But += really means extend
>>> L, M # M sees the in-place change too!
([1, 2, 3, 4], [1, 2, 3, 4])

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

>>> x = print('spam') # print is a function call expression in 3.X


spam
>>> print(x) # But it is coded as an expression statement
None

Expression Statements and In-Place Changes


>>> L = [1, 2]
>>> L.append(3) # Append is an in-place change
>>> L
[1, 2, 3]

>>> L = L.append(4) # But append returns None, not L


>>> print(L) # So we lose our list!
None

Print Operations
File object methods

file.write(str)).

Standard output stream


The standard output stream (often known as stdout) is simply a default place to
send a program’s text output.

The Python 3.X print Function

You might also like