Control flow ↩
Control flow statements
You can set a conditional construct with if / elif / else keywords:
number = 10
if number < 20:
print('less than twenty')
elif 20 <= number < 40:
print('between twenty and forty')
else: # number >= 40
print('more than forty')
Python supports two flavours of loops, for
and while
loops.
For loops are designed to browse sequences (or iterables). They provide an identifier pointing to the element made available at each cycle, eachChr
in this case
for eachChr in 'some string':
print(eachChr)
While loops instead are an extension of a simple conditional construct. They keep cycling until a certain condition is evaluated as True
from random import random
switch = True
while switch:
print('looping...')
if random() < 0.2:
switch = False
The ‘try’ statement
# setup
try:
# action
finally:
# cleanup
finally
is always executed, even if the code that does the work doesn’t finish
The ‘with’ statement
The with
statement offers a convenient syntax to express the common pattern of setting up a context, perfoming an action, and then cleaning up when done.
A with
statement works together with a context manager – an object that handles the entry into and exit from a context, encapsulating the setup and cleanup actions.
Here are a few examples of with
in use, and the corresponding code without it:
Opening a file, processing its contents, and closing the file:
with open('example.txt', 'r') as f:
txt = f.read()
# same as:
f = open('example.txt', 'r') # setup
try:
txt = f.read() # action
finally:
f.close() # cleanup
Managing the graphics state in DrawBot:
with savedState():
scale(1.5)
# same as:
save() # setup
scale(1.5) # action
restore() # cleanup
Managing undo history in RoboFont (first option is preferred):
with glyph.undo():
glyph.removeOverlap()
# same as:
glyph.prepareUndo() # setup
glyph.removeOverlap() # action
glyph.performUndo() # cleanup