Lesson 4 - Control Structures
Up until now, we’ve been executing lines sequentially, one after another. With control structures, we can execute lines conditionally or even create loops of instructions.
Table of Contents
Lesson Objectives
- Conditionally execute code using
ifstatements. - Loop code using
whileloops andforloops. - Learn about the
pass,break, andcontinuekeywords.
Conditional Statements
if Statements
With conditional statements, we can test a boolean expression to decide whether or not to execute lines of code. In Python, this is done using an if statement.
if expression:
line1
line2
line3
Take a look at the code block above. This is the general structure of an if statement. If the expression is evaluation to be True, line1 and line2 will execute. Otherwise, if the expression is evaluated to be False, Python will skip over line1 and line2.
An important part of Python that we haven’t discussed yet is the indentation. With if statements, anything you want to be included within the conditional statement needs to be indented with a Tab. In the example above, line1 and line2 are conditionally executed, whereas line3 will always be executed since it is not part of the if statement.
else Blocks
Occasionally, you’ll need to have two seperate pieces of code. One if the condition succeeds, and one if the condition fails. You can use the else keyword to do just that!
if expression:
line1
line2
else:
line3
In the example above, line1 and line2 are executed if the expression evaluates to be True. Otherwise, if the expression evaluates to be False, line3 will be executed.
elif Blocks
Sometimes, if and else is not enough. You might need to test multiple ranges of numbers. This is where the elif keyword comes in.
if expression:
line1
elif expression2:
line2
else:
line3
In the example above, line1 is executed if expression evalutes to be True. If and only if expression evaluates to be False, it will test expression2. If expression2 is True, line 2 will be executed. Otherwise, line3 will be executed.
Extra Exercises
Loops
In Python, there’s often a need to repeat pieces of code multiple times, whether they’re exactly the same or with a slight variance. There are two different control structures to deal with looping, while loops and for loops.
while Loops
while loops are used to repeat a piece of code until an expression evaluates to be False.
while expression:
line1
line2
line3
The code above would run line1 and line2 repeatedly until the expression is False. You can easily run into an infinite loop if you forget about the expression. For the loop to terminate, a part of the code inside the while loop has to modify the expression in some way.
Just like if statements, code inside while loops needs to be indented.
for Loops
for loops also repeat pieces of code, just like while loops. However, the number of times a for loop repeats is based on the number of items in an “iterable”. An iterable is an object that is capable of returning items one at a time. A great example of an iterable is a list.
for x in [1,2,3]:
line1
In the code block above, line1 will execute 3 times. Every time a new loop starts, x is set to the value of the current iterable, meaning that we can use x as part of our code.
Code inside for loops also needs to be indented.
Input
for x in [1,2,3]:
print(x)
Output
1
2
3
range() is a useful function for creating for loops. range(x) automatically creates a list from 0 to x (exclusive) for the loop to iterate over.
Input
for x in range(5):
print(x)
Output
0
1
2
3
4
Pass, Break, and Continue
There are three keywords that occasionally find use in loops, pass, break and continue.
Pass
If you want to create an conditional statement or loop and leave it empty, you need to use the pass keyword. Python will give you an error if you leave it blank.
if expression:
pass
for x in range(5):
pass
Break
If you decide you want to “break” out of a while loop before the condition evaluates to False, or a for loop before it finishes iterating over the items, you can use break.
Input
myList = [5, 3, "word", 2, 6]
mySum = 0
for item in myList:
# If the item is not an integer, reset the sum, send an error message, and break out of the loop.
if type(item) != type(1):
mySum = 0
print("ERR: This list contains an item that is not an integer.")
break
else:
mySum = mySum + item
print(f"The sum is {mySum}.")
Output
ERR: This list contains an item that is not an integer.
The sum is 0.
Continue
Rather than breaking out of a loop, you can also continue. continue skips the rest of the current iteration and moves onto the next one.
Input
myList = [5, 3, "word", 2, 6]
mySum = 0
for item in myList:
# If the item is not an integer, send an error message and continue to the next iteration of the loop.
if type(item) != type(1):
print("ERR: This list contains an item that is not an integer.")
continue
else:
mySum = mySum + item
print(f"The sum is {mySum}.")
Output
ERR: This list contains an item that is not an integer.
The sum is 16.
Key Points / Summary
- You can use the
if,else, andelifto create conditionally executed code. - You can also use
forandwhileto create loops. - Use
passto fill up empty conditional statements or loops and prevent errors. breakandcontinuecan skip iterations of a loop, or stop the loop completely.