Control Flow

What we’ll cover

Block Scope

Conditional Statements

If Statements General Syntax

if(condition): # this is a check
    statement1
    statement2

If Statements Example

if(5 > 10): # this is a check
    print("5 is greater than 10!")

If/Else Statements General Syntax

if (condition):
    statement1
else:
    statement2

If/Else Statements Example

if (condition1):
    statement1
elif(condition2):
    statement2

If/Else If Statements General Syntax

if (condition):
    statement1
elif(condition2):
    statement2
else:
    statement3

Loops

The while loop executes a statement (which may be a block statement) while a condition is true

while(condition):
    statement

The while loop will never execute if the condition is false at the outset

If you want to make sure a block is executed at least once, ensure the initial condition is set to True, then internally changed to False to break out of the loop

check_condition = True
while(check_condition):
    if(some_break_condition):
        check_condition = False

Determinate Loops

The for loop is a general construct to support iteration controlled by a counter or similar variable that is updated after every iteration.

for i in range(10):
    print(i)

Nested Loops

You can have loops within loops, but be aware of variable scoping:

for i in range(5):
  for j in range(5):
    print(j)

Statements That Break Control Flow

The same break statement that you use to exit a switch can also be used to break out of a loop

payment_per_year = 10000
interest_rate = 0.05
current_year = 0
balance = 0
while (current_year <= 100):
    balance += payment_per_year
    interest = balance * interest_rate / 100
    balance += interest
    if (balance >= goal):
        break
    current_year += 1

The continue statement transfers control to the header of the innermost enclosing loop

while (sum < goal):
    input_number_as_string = input("Enter a number: ")
    input_number_as_integer = int(input_number_as_string)
    if (input_number_as_integer == 0):
        continue
    sum += n # not executed if `input_number_as_integer` is 0