Control Flow Basics in Python - A Guide to Loops
What is Control Flow?
By definition, control flow determines the order in which instructions are executed in our programs. Moreover, it refers to the process of directing the flow of execution based on conditions or factors that we specify.
That being said, loops represent a key component of control flow in Python, as they allow us to repeat a block of code multiple times and loop over iterable objects. Alongside additional statements, we can automate repetitive tasks, such as processing data, printing patterns, or performing elaborate calculations.
The Python For Loop
For demonstration purposes, we'll start with rudimentary examples and observe how the for
loop works. With it, we can iterate over a sequence of items, such as a list, tuple, or string. The basic structure of a for loop in Python is as follows:
for item in sequence:
# code to be executed for each item in the sequence
Observe how we can iterate over a list of numbers in a list:
numbers = [1, 2, 3, 4, 5]
for num in numbers:
print(num)
The output is as follows:
1
2
3
4
5
Note that we're not limited to just lists and numbers. We can loop over a wide range of iterable objects, including tuples, dictionaries, sets, and even strings.
For Loops with range()
You might be familiar with this built-in function from the Python data types overview that we previously covered.
The range()
function helps us generate a sequence of numbers proving useful when we need to iterate over a specific range.
for i in range(5):
print(i)
This code will output the following:
0
1
2
3
4
Notice that the output doesn't include 5, since the counting starts from 0 as an initial value.
For Loops with else
When we use the else
clause in combination with a for
loop, we specify a block of code that should be executed after the loop has finished. However, this will only occur if the loop isn't terminated by a break
statement, which we'll learn about in the sections below.
numbers = [1, 2, 3, 4, 5]
for num in numbers:
if num % 2 == 0:
print(f"{num} is an even number")
else:
print("All numbers have been processed")
The output we get is the following:
2 is an even number
4 is an even number
All numbers have been processed
The Python While Loop
The while
loop repeats a block of code, or multiple statements, as long as the given condition is true. The basic structure of a while loop in Python is as follows:
while condition:
# code to be executed while the condition is met
For instance, we can print out a sequence of numbers as long as the variable i
is less than or equal to 5, like so:
i = 1
while i <= 5:
print(i)
i += 1
Output:
1
2
3
4
5
Control Statements in Python
With control statements such as break
and continue
we can make decisions that change the direction of our code and introduce some flexibility.
The break
Statement
We use break
to exit a loop prematurely and move on to the next statement after the loop. Simply put, it terminates the loop and transfers execution to the next line of code outside of it.
mining = ["silver", "copper", "gold", "rocks"]
for ore in mining:
if ore == "gold":
print("Found gold! Breaking the loop...")
break
print(ore)
This code will output the following:
silver
copper
Found gold! Breaking the loop...
The continue
Statement
The continue statement allows you to skip the current iteration of a loop and continue with the next iteration. This can be useful when you want to skip certain conditions or values in a loop.
Here's an example of using the continue statement in a for loop to extract the initials of a name:
full_name = "Bob Odenkirk"
initials = ""
for char in full_name:
if not char.isupper():
continue
initials += char
print(initials)
# Output: BO
Let's break it down. First, we create a variable and assign it the full name. We then initialize an empty string to store the initials. Then, the loop iterates over each character in the string, and with the isupper()
method we check if the character is uppercase. If so, the continue
statement is executed and the loop moves on to the next iteration, skipping the current one. If the character is uppercase, it will be added to the initials variable with +=
operator. to the initials string using the += operator.
Nested Loop Examples
Potentially, we can complicate things even further by nesting loops within loops. Logically, this allows us to perform operations on the elements of multiple lists or other iterable objects simultaneously.
for i in range(1, 11):
for j in range(1, 11):
print(i * j, end='\t')
print()
As we can see, the nested loop structure carried out multiplications on all the combinations of numbers from 1 to 10.
1 2 3 4 5 6 7 8 9 10
2 4 6 8 10 12 14 16 18 20
3 6 9 12 15 18 21 24 27 30
4 8 12 16 20 24 28 32 36 40
5 10 15 20 25 30 35 40 45 50
6 12 18 24 30 36 42 48 54 60
7 14 21 28 35 42 49 56 63 70
8 16 24 32 40 48 56 64 72 80
9 18 27 36 45 54 63 72 81 90
10 20 30 40 50 60 70 80 90 100
Final Thoughts
A solid understanding of loops and control flow in Python is a must-have for any programmer. However, loops don't have to be used in isolation. They can be combined with other control flow statements, such as conditionals and functions, to create more complex and powerful programs. We encourage you to experiment and combine various elements, to achieve more compelling results.