Flow of Control

Overview

  • Data basics
    • Theory of types
    • Basic types
    • Composite types: Tuples, lists and dictionaries
  • Functions
    • range() function
    • read and write files
  • Flow control
    • If
    • for

Flow of Control


Flow control figure

Flow control refers how to programs do loops, conditional execution, and order of functional operations. Let's start with conditionals, or the venerable if statement.

Let's start with a simple list of instructors for these classes.


In [1]:
instructors = ['Dave', 'Joe', 'Dorkus the Clown']
instructors


Out[1]:
['Dave', 'Joe', 'Dorkus the Clown']

In [2]:
print("dave")


dave

In [3]:
for instructor in instructors:
    print(instructor)


Dave
Joe
Dorkus the Clown

In [4]:
for idx in range(len(instructors)):
    print(instructors[idx])


Dave
Joe
Dorkus the Clown

If

If statements can be use to execute some lines or block of code if a particular condition is satisfied. E.g. Let's print something based on the entries in the list.


In [5]:
for instructor in instructors:
    if not "Clown" in instructor:
        print(instructor)
    else:
        pass


Dave
Joe

In [6]:
for instructor in instructors:
    if "Clown" in instructor:
        pass
    else:
        print(instructor)


Dave
Joe

In [8]:
for instructor in instructors:
    if not "Clown" in instructor:
        print(instructor)
    elif not "z" in instructor:
        print(instructor)
    else:
        pass


Dave
Joe
Dorkus the Clown

In [ ]:
if 'Dorkus the Clown' in instructors:
    print('#fakeinstructor')

Usually we want conditional logic on both sides of a binary condition, e.g. some action when True and some when False


In [ ]:
if 'Dorkus the Clown' in instructors:
    print('There are fake names for class instructors in your list!')
else:
    print("Nothing to see here")

There is a special do nothing word: pass that skips over some arm of a conditional, e.g.


In [ ]:
if 'Joe' in instructors:
    print("Congratulations!  Joe is teaching, your class won't stink!")
else:
    pass

Note: what have you noticed in this session about quotes? What is the difference between ' and "?

Another simple example:


In [ ]:
if True is False:
    print("I'm so confused")
else:
    print("Everything is right with the world")

It is always good practice to handle all cases explicity. Conditional fall through is a common source of bugs.

Sometimes we wish to test multiple conditions. Use if, elif, and else.


In [ ]:
my_favorite = 'pie'

if my_favorite is 'cake':
    print("He likes cake!  I'll start making a double chocolate velvet cake right now!")
elif my_favorite is 'pie':
    print("He likes pie!  I'll start making a cherry pie right now!")
else:
    print("He likes " + my_favorite + ".  I don't know how to make that.")

Conditionals can take and and or and not. E.g.


In [ ]:
my_favorite = 'pie'

if my_favorite is 'cake' or my_favorite is 'pie':
    print(my_favorite + " : I have a recipe for that!")
else:
    print("Ew!  Who eats that?")

For

For loops are the standard loop, though while is also common. For has the general form:

for items in list:
    do stuff

For loops and collections like tuples, lists and dictionaries are natural friends.


In [ ]:
for instructor in instructors:
    print(instructor)

You can combine loops and conditionals:


In [ ]:
for instructor in instructors:
    if instructor.endswith('Clown'):
        print(instructor + " doesn't sound like a real instructor name!")
    else:
        print(instructor + " is so smart... all those gooey brains!")

In [1]:
# Loops can be nested
for i in range(1, 4):
    for j in range(1, 4):
        print('%d * %d = %d' % (i, j, i*j))  # Note string formatting here, %d means an integer

# Can exist loop if a condition is met
for i in range(10):
    if i == 4:
        break


1 * 1 = 1
1 * 2 = 2
1 * 3 = 3
2 * 1 = 2
2 * 2 = 4
2 * 3 = 6
3 * 1 = 3
3 * 2 = 6
3 * 3 = 9

Programming Example

Write a script that finds the first N prime numbers.


In [12]:
4 % 2


Out[12]:
0

In [21]:
N = 100
for candidate in range(2, N):
    # n is candidate prime. Check if n is prime
    is_prime = True
    for m in range(2, candidate):
        if (candidate % m) == 0:
            is_prime = False
            break
    if is_prime:
        print("%d is prime!" % candidate)


2 is prime!
3 is prime!
5 is prime!
7 is prime!
11 is prime!
13 is prime!
17 is prime!
19 is prime!
23 is prime!
29 is prime!
31 is prime!
37 is prime!
41 is prime!
43 is prime!
47 is prime!
53 is prime!
59 is prime!
61 is prime!
67 is prime!
71 is prime!
73 is prime!
79 is prime!
83 is prime!
89 is prime!
97 is prime!