Skip to content

Latest commit

 

History

History
50 lines (38 loc) · 1.52 KB

File metadata and controls

50 lines (38 loc) · 1.52 KB

Changing the Control Flow

In many of these examples so far, we see a very simple control flow. The program starts at the first line, and just goes line by line until runs out of statements.

q = 0
j = 5
q = j * 4 - 20
print(q) # -> 0

When programs start to get more sophisticated, the control flow can be changed.

peoplePerTable = 5
tables = 8

maximumRoomOccupancy = tables * peoplePerTable
# up to this point we just stepped line by line

if (bridesDesiredPartySize > maximumRoomOccupancy):
    canHandleThisReception = False
else:
    canHandleThisReception = True

See how the IF statement can change a variable based on a decision about another variable? We are changing the control flow based on the state of the data within the program!

There are various conditional statements, loop statements, and functions that can cause the control flow to move around within the code. Here we see using both a loop and a conditional IF statement to change the flow of control.

q = 0
j = 6
while (j > 0) :
    q = j * 4 - 20
    print(q)
    j -= 1  # Hey! this how you can decrement by 1
    if (q > 0) :
        print("q is still positive")

This ability to manipulate the control flow of a program is very important when you start developing logic for your apps and programs. Logic in programs depends heavily on being able to manipulate the control flows through the code. Let’s take a look at how each kind of statement allows a programmer to change the flow of control in programs.