See also docs.python.org / Tutorial / More Control Flow Tools
↓ condition
if pianist.is_here :
play_an_introduction()
↑ action
Colon and indent instead of curly braces for blocks
if (x < 5):
# four spaces indent is recommended
print(x)
Parentheses around condition aren’t necessary
if x < 5 :
# omit parentheses
print(x)
Parentheses around condition aren’t necessary
if x < 5 and y > 7:
# omit parentheses when possible
print(x)
See also docs.python.org / Tutorial / Expressions # Operator precedence
# instead of
if temperature > 21 and temperature < 26:
# write
if 21 < temperature < 26:
'''
Comfortable
'''
# or even
if 21 < outdoor_temperature < indoor_temperature < 26:
'''
Comfortable but external temperature
is a bit lower than internal one
'''
if x < 5:
print(x)
else:
# otherwise
print(something_else)
elif
if x < 5:
print('Few')
elif x > 9:
# second condition
print('Many')
else:
print(something_else)
elif
if x < 5:
print('Few')
elif x > 9:
# second condition
print('Many')
else:
print(something_else)
elif
if x < 5:
print('Few')
elif x > 9:
print('Many')
elif x > 7:
print('Not so many')
elif z == 42:
switch
operator
elif
s
=
is not a comparison operator
>>> if z = 7:
File "<stdin>", line 1
if z = 7:
^
SyntaxError: invalid syntax
=
and ==
z = 7
if z == 42:
print(z)
if x < 5:
z = 'Few'
else:
z = 'Many'
if x < 5:
z = 'Few'
else:
z = 'Many'
z = 'Few' if x < 5 else 'Many'
if pianist.is_here :
play_an_introduction()
play_an_introduction()
SomeError: we have no pianist to play anything
>>> stuff = ['hydrogen', 'helium', 'lithium']
>>> number = input('Enter number of element ')
Enter number of element 42
>>> print(stuff[int(number)])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list index out of range
try
statement>>> try:
... print(stuff[int(number)])
... except IndexError:
... print(f'Wrong index. Use number less than {len(stuff)}')
...
Wrong index. Use number less than 3
number == 'z'
?>>> try:
... print(stuff[int(number)])
... except IndexError:
... print(f'Wrong index. Use number less than {len(stuff)}')
...
Traceback (most recent call last):
File "", line 2, in
ValueError: invalid literal for int() with base 10: 'z'
>>> try:
... print(stuff[int(number)])
... except IndexError:
... print(f'Wrong index. Use number less than {len(stuff)}')
... except ValueError:
... print(f'Index must be an integer number')
else
when there is no exception>>> try: # number == 2
... print(stuff[int(number)])
... # skipped
... else:
... print('OK')
...
lithium
OK
finally
is executing after all checks... # skipped
... else:
... print('OK')
... finally:
... print("That's all, folks!")
...
lithium
OK
That's all, folks!
finally
is executing after all checks>>> try:
... print(stuff[int(number)])
... except IndexError:
... print(f'Wrong index...
... # skipped
... finally:
... print("That's all, folks!")
number
is wrong
Wrong index. Use number less than 3
That's all, folks!
with
with open('/etc/timezone', 'r') as f:
for line in f:
print(line)
# same as
f = open('/etc/timezone', 'r')
for line in f:
print(line)
with
implicitly calls methods# __enter__
with open('/etc/timezone', 'r') as f:
for line in f:
print(line)
# __exit__
class Writer:
def __init__(self, file_name):
self.file_name = file_name;
def __enter__(self):
self.file = open(self.file_name, 'w')
return self.file;
def __exit__(self, exc_type, exc_value, traceback):
self.file.close()
with Writer('file.txt') as f:
f.write('hello world')
class Writer:
def __init__(self, file_name):
self.file_name = file_name;
def __enter__(self):
self.file = open(self.file_name, 'w')
return self.file;
def __exit__(self, exc_type, exc_value, traceback):
self.file.close()
with Writer('file.txt') as f:
f.write('hello world')
# Writer.__exit__
class Writer:
def __init__(self, file_name):
self.file_name = file_name;
def __enter__(self):
self.file = open(self.file_name, 'w')
return self.file;
def __exit__(self, exc_type, exc_value, traceback):
self.file.close()
for
loop
for item in sequence:
# do something
people = ['Alice', 'Bob', 'Charlie']
for person in people:
print(person)
teen = range(13, 20)
for age in teen:
print(f'Age is {age}')
teen = range(13, 20)
for age in teen:
print(f'Age is {age}')
for i in range(10):
do_something() # ten times
i
, j
, k
(and x
, y
, z
) are good names for counter variables
for x in width:
for y in height:
for z in depth:
do_something(x, y, z)
Put a loop inside another one
for x in width:
for y in height:
for z in depth:
do_something(x, y, z)
colors = ['red', 'orange', 'yellow' ]
people = ['Alice', 'Bob', 'Charlie' ]
fruits = ['apple', 'banana', 'cucumber']
colors = ['red', 'orange', 'yellow' ]
people = ['Alice', 'Bob', 'Charlie' ]
fruits = ['apple', 'banana', 'cucumber']
colors = ['red', 'orange', 'yellow' ]
people = ['Alice', 'Bob', 'Charlie' ]
fruits = ['apple', 'banana', 'cucumber']
colors = ['red', 'orange', 'yellow' ]
people = ['Alice', 'Bob', 'Charlie' ]
fruits = ['apple', 'banana', 'cucumber']
>>> for color, name, fruit in zip(colors, people, fruits):
... print(f'{name} has {color} {fruit}')
...
Alice has red apple
Bob has orange banana
Charlie has yellow cucumber
>>> stuff = ['hydrogen', 'helium', 'lithium']
>>> stuff = ['hydrogen', 'helium', 'lithium']
>>> for i in range(len(stuff)):
... print(i + 1, stuff[i])
...
1 hydrogen
2 helium
3 lithium
>>> for number, name in zip(range(1, len(stuff) + 1), stuff):
... print(number, name)
...
1 hydrogen
2 helium
3 lithium
>>> for number, name in enumerate(stuff):
... print(number, name)
...
0 hydrogen
1 helium
2 lithium
>>> for number, name in enumerate(stuff, start=1):
... print(number, name)
...
1 hydrogen
2 helium
3 lithium
>>> fruits = {
'apple': 'red',
'banana': 'yellow',
'cucumber': 'green',
}
>>> fruits = {'apple': 'red', 'banana': 'yellow', 'cucumber': 'green'}
>>> fruits.items()
dict_items([('apple', 'red'), ('banana', 'yellow'), ('cucumber', 'green')])
>>> fruits.keys()
dict_keys(['apple', 'banana', 'cucumber'])
>>> fruits.values()
dict_values(['red', 'yellow', 'green'])
>>> fruits = {'apple': 'red', 'banana': 'yellow', 'cucumber': 'green'}
>>> fruits.items()
dict_items([ ('apple', 'red'), ('banana', 'yellow'), ('cucumber', 'green')] ] )
List of tuples
>>> for fruit, color in fruits.items():
... print(f'{fruit} is {color}')
...
apple is red
banana is yellow
cucumber is green
>>> for fruit in fruits.keys():
... print(fruits[fruit], fruit)
...
red apple
yellow banana
green cucumber
while condition:
# do something
>>> rest = 3
>>> while rest > 0:
... print(f'Rest is {rest}')
... rest -= 1
...
Rest is 3
Rest is 2
Rest is 1
>>> rest = 3
>>> while rest:
... print(f'Rest is {rest}')
... rest -= 1
...
Rest is 3
Rest is 2
Rest is 1
>>> rest = 3
>>> while rest:
... print(f'Rest is {rest}')
... rest -= 1
variable += delta # increase
variable -= delta # decrease
Unlike C, C++, Java, JavaScript, Perl, PHP, Ruby etc
++
and --
operators++
and --
operators>>> 3++2 # 3 + +2
5
>>> 4--5 # 4 − (−5) = 4 + 5
9
++
and --
operators>>> 7++
File "", line 1
7++
^
SyntaxError: invalid syntax
continue
>>> for i in range(1, 5):
... if i < 3: continue
... print(i)
...
3
4
break
>>> for i in range(1, 55):
... print(i)
... if i > 2: break
...
1
2
3
do:
# do something
until condition
do:
# do something
until condition
break
to emulate it
>>> while True: # infinite loop
... amount = input('How many? Or type q to quit ')
... if amount == 'q':
... break
...
How many? Or type q to quit 4
How many? Or type q to quit q
Refrain is part of code
Such parts named
Refrain is part of code
def
ine a function>>> def refrain(how):
... print('Chorus')
...
()
are required>>> def refrain():
... print('Chorus')
...
>>> refrain()
Chorus
()
are required>>> refrain()
Chorus
>>> refrain # without parentheses
<function refrain at 0x7faf21a710d0>
pass
>>> def do_nothing():
... pass
...
>>> do_nothing()
>>> refrain()
Chorus
>>> duration = sing('Quick brown fox jumps')
>>> def refrain(text, count):
... print(str(text) * int(count))
...
>>> refrain('Yeah! ', 3)
Yeah! Yeah! Yeah!
>>> def refrain(text, count):
... print(str(text) * int(count))
...
>>> refrain(42, 3)
424242
>>> refrain(42, '7')
42424242424242
>>> def refrain(text, count):
... print(str(text) * int(count))
...
>>> refrain(count=5, text='Five! ')
Five! Five! Five! Five! Five!
def production(*args):
result = 1
for number in args:
result *= number
return result
>>> production(6, 7)
42
>>> production(3, 5, 7)
105
>>> production(1, 2, 3, 4, 5)
120
>>> production('🐍', 2, 10)
'🐍🐍🐍🐍🐍🐍🐍🐍🐍🐍'
>>> production(range(1, 70))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 7, in production
TypeError: unsupported operand type(s) for *=: 'int' and 'range'
*
>>> production(range(1, 7))
... TypeError: unsupported operand type(s) for *=:
'int' and 'range'
>>> production(list(range(1, 7)))
[1, 2, 3, 4, 5, 6]
>>> production(*range(1, 7))
720 # = 1 × 2 × 3 × 4 × 5 × 6 = 6!
*
>>> production(*range(1, 7))
720 # = 1 × 2 × 3 × 4 × 5 × 6 = 6!
*
outside argument list>>> *range(1, 7)
File "<stdin>", line 1
SyntaxError: can't use starred expression here
>>> print(*range(1, 7))
1 2 3 4 5 6
*
works with various iterators>>> print(*range(1, 7))
1 2 3 4 5 6
>>> print(*zip(['apple', 'banana'], ['red', 'yellow']))
('apple', 'red') ('banana', 'yellow')
>>> print(*enumerate(['H', 'He', 'Li', 'Be', 'B'], start=1))
(1, 'H') (2, 'He') (3, 'Li') (4, 'Be') (5, 'B')
>>> def sing(**kwargs):
... print(f'We sing a song named {kwargs["name"]} '
... + f'in key {kwargs["key"]} using tempo '
... + kwargs["tempo"])
...
>>> sing(name='Yesterday', tempo='96 bpm', key='F dur')
We sing a song named Yesterday in key F dur using tempo 96 bpm
>>> sos = {'name': 'S. O. S.', 'key': 'A moll',
... 'tempo': 'Allegro'}
>>> sing(sos)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: sing() takes 0 positional arguments but 1 was given
**
to expand dict>>> sing(**sos)
We sing a song named S. O. S. in key A moll using tempo Allegro
**
outside argument list>>> **sos
File "<stdin>", line 1
**sos
^
SyntaxError: invalid syntax
>>> print(**sos)
Traceback (most recent call last):
File <stdin>", line 1, in <module>
TypeError: 'name' is an invalid keyword argument for print()
>>> args = {'sep': '/', 'end': '!\n'}
>>> print('Some', 'sequence', 'here', **args)
Some/sequence/here!
*
and **
together>>> args = {'sep': '/', 'end': '!\n'}
>>> stuff = ['H', 'He', 'Li', 'Be', 'B']
>>> print(stuff, **args)
['H', 'He', 'Li', 'Be', 'B']!
>>> print(*stuff, **args)
H/He/Li/Be/B!
def do_something():
# something
def do_something_else():
# something else
result = do_something() + do_something_else()
import something
result \
= something.do() \
+ something.do_more()
print(result) # 1042
# something.py
def do():
return 1000
def do_more():
return 42
import
import something
# unexpected
# Oops!
# something.py
def do():
# skipped
print('Oops!')
import something
# without any surprize
# something.py
def do():
# skipped
if __name__ == '__main__':
print('Oops!')
import something as s
result \
= s.do() \
+ s.do_more()
print(result) # 1042
# something.py
def do():
return 1000
def do_more():
return 42
import
# import something
from something import do, do_more
result = do() + do_more()
print(result)
dir
lists methods of imported module>>> import something
>>> dir(something)
['__builtins__', '__cached__', '__doc__', '__file__',
'__loader__', '__name__', '__package__', '__spec__',
'do', 'do_more']
dir
>>> import something as s
>>> dir(something)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'something' is not defined
>>> dir(s)
['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'do', 'do_more']
>>> from datetime import date
>>> date.today()
datetime.date(2020, 11, 22)
>>> from datetime import date as d
>>> d.fromtimestamp(1555444333)
datetime.date(2019, 4, 17)
>>> import math as m
>>> m.sqrt(65536) # square root
256.0
More than 200 modules which are already installed and usually ready to use
# import-re.py
import re
print('Who is there?')
m = re.match(r'\w', 'S')
# re.py
def some():
return 'thing'
print('Local re module')
python3 import-re.py
Local re module
Who is there?
Traceback (most recent call last):
File "import-re.py", line 4, in <module>
m = re.match(r'\w', 'S')
AttributeError: module 're' has no attribute 'match'
Each module also comes with a one-line summary of what it does; to list the modules whose name or summary contain a given string such as "spam", type "modules spam".
>>> help('modules graph')
>>> help('modules graph')
Here is a list of modules whose name or summary contains 'graph'.
If there are any, enter a module name to get more help.
secrets - Generate cryptographically strong pseudo-random numbers suitable for
turtle - Turtle graphics is a popular way for introducing programming to
Crypto - Python Cryptography Toolkit
>>> help('modules statistic')
Here is a list of modules whose name or summary contains 'statistic'.
If there are any, enter a module name to get more help.
statistics - Basic statistics module.
help
on a module>>> import(statistics)
>>> help(statistics)
Help on module statistics:
NAME
statistics - Basic statistics module.
...
docs.python.org / Installing Python Modules
Install MODULENAME system-wide for Debian GNU/Linux and its derivatives (Ubuntu, Mint)
sudo apt install python3-MODULENAME
Install local copy of modules
sudo apt install python3-venv
python3 -m venv venv
. venv/bin/activate
pip install MODULENAME
Read the documentation for your system.