NB: On Control Structures

Topics:

Introducing Control Structures

Python includes structures to control the flow of a program:

  • conditions (if, else)
  • loops
    • while-loop
      Execute statements while a condition is true
    • for-loop
      Iterates over a iterable object (list, tuple, dict, set, string)

Indentation

This is where Python differs from most languages. To define control structures,
and functional blocks of code in general, most languages use either characters like braces { and } or key words like IF ... END IF.

Python uses tabs – spaces, actually – to signify logical blocks off code.

It is therefore imperative to understand and get a feel for indentation. For more information, see Lutz 2019, “A Tale of Two Ifs.”

Conditions

if and else can be used for conditional processing.

val = -2

if val >= 0:
    print(val)
else:
    print(-val)
2

elif

elif is reached when the previous statements are not.

val = -2

if -10 < val < -5:
    print('bucket 1')
elif -5 <= val < -2:
    print('bucket 2')
elif val == -2:
    print('bucket 3')
bucket 3

else

else can be used as a catchall

val = 5

if -10 < val < -5:
    print('bucket 1')
elif -5 <= val < -2:
    print('bucket 2')
elif val == -2:
    print('bucket 3')
else:
    print('bucket 4')
bucket 4

if and else as one-liners

x = 3
print('odd') if x % 2 == 1 else print('even')
odd

Notice == for checking the condition x % 2 == 1.

both if and else are required. This breaks:

print('odd') if x % 2 == 1
SyntaxError: invalid syntax (471325368.py, line 1)

Using multiple conditions

If statements can be complex combinations of expressions.

Use parentheses carefully, to keep order of operations correct.

## correct

val = 2

if (-2 < val < 2) or (val > 10):
    print('bucket 1')
else:
    print('bucket 2')
bucket 2
## incorrect - misplaced parenthesis

if (-2 < val) < 2 or val > 10:
    print('bucket 1')
else:
    print('bucket 2')
bucket 1

and this is because True < 2, as True is cast to integer value 1

this is not the desired result…but does it make sense?

Loops

while

What does this print?

ix = 1
while ix < 10:
    ix = ix * 2
print(ix)
16

break to exit the loop altogether

sometimes you want to quit the loop early, if some condition is met.
uses if-statement

ix = 1
while ix < 10:
    ix = ix * 2
    if ix == 4:
        break
print(ix)
4

The break causes the loop to end early

continue to stop the current iteration

sometimes you want to introduce skipping behavior in the loop.
uses if-statement

ix = 1
while ix < 10:
    ix = ix * 2
    if ix == 4:
        print('skipping 4...')
        continue
    print(ix)
2
skipping 4...
8
16

The continue causes the loop to skip printing 4

for

iterate over an iterable

cities = ['Charlottesville','New York','SF','BOS','LA']

for city in cities:
    city = city.lower()
    print(city)
charlottesville
new york
sf
bos
la

quit early if SF reached, using break

cities = ['Charlottesville','New York','SF','BOS','LA']

for city in cities:
    if city == 'SF':
        break
    city = city.lower()
    print(city)
charlottesville
new york

skip over SF if reached, using continue

cities = ['Charlottesville','New York','SF','BOS','LA']

for city in cities:
    if city == 'SF':
        continue
    city = city.lower()
    print(city)
charlottesville
new york
bos
la

while vs for

For loops are used to loop through a list of values or an operation in which the number of iterations is known in advance.

While loops are when you don’t know how many interations it will take – you are depending on some condition to be met.

It is possible for while loops to be unending, for example:

while 1:
    print("This is so annoying")