Control Flow

07_control_flow

Control Flow

There are three basic types of control flow operation; Branch, Iteration and Jump. The most powerful of the three is Jump. In the early days of programming we used a dark art known as goto to jump from one section of code to another. Programming is more civilized now, instead of goto we use the invocation of a functor for that same behavior. Functions will be covered in the next module.

  • Branch
  • Iteration
  • Jump: see Functor
In [0]:
import random
In [2]:
animal = random.choice(("Cat", "Dog", "Bug"))

if animal == "Cat":
    print("Mew")
elif animal == "Dog":
    print("Wuf")
else:
    print("Buz")
Buz
In [3]:
print("heads" if random.randint(0, 1) == 1 else "tails")
tails

Loop Counter

In [4]:
counter = 0

while True:
    if counter >= 42:
        break
    else:
        counter += 1

print(counter)
42

Range Based For Loop

In [5]:
for num in range(10):
    print(num * 10)    
0
10
20
30
40
50
60
70
80
90

For Each Loop

In [6]:
some_list = [
    "Alpha",
    "Beta",
    "Gamma",
    "Delta",
    "Zeta",
]

for itm in some_list:
    print(itm)
Alpha
Beta
Gamma
Delta
Zeta

Enumeration

In [7]:
for idx, val in enumerate(some_list):
    print(idx, val)
0 Alpha
1 Beta
2 Gamma
3 Delta
4 Zeta
In [0]: