In the previous post, we discussed different operator types, some of them are useful when performing mathematical computations, and others are useful when performing logical operations. If you feel like you need a refresher on that matter, you can find it by following the link. 👇👇👇
Now it's time to understand how to control program flow with loops and conditional statements.
Previously, we wrote a script that printed "Hi, PyCharm" three times.
def print_hi(name):
greetings = f'Hi, {name}'
print(greetings)
print(greetings)
print(greetings)
if __name__ == '__main__':
print_hi('PyCharm')
To achieve that, we copied and pasted the print(...) function three times and extracted the greetings message into a variable. The solution works but is cumbersome. And if we wanted to print that message a million times, would we copy and paste that code a million times? The answer is no because Python has the means to address repetitive fragments of code. Those means are called loops.
Loops in programming are structures that allow you to execute a block of code repeatedly. They are used to automate repetitive tasks and perform operations multiple times without having to write the same code over and over again. Loops are essential for improving the efficiency and readability of your programs.
There are two main types of loops in Python: while
loops and for
loops.
While loops
A while
loop is a control structure that repeatedly executes a block of code as long as a specified condition remains True
. This type of loop is particularly useful when the number of iterations is not known in advance, and we want to keep executing a certain block of code until a condition is met.
Here's the basic structure of a while
loop:
while condition:
# Code to be executed
The loop will continue to execute the code block as long as the condition
remains True
. Once the condition becomes False
, the loop stops and the program continues with the next statement after the loop.
Here's an example that demonstrates the concept of a while
loop.
count = 0
while count < 5:
print(count)
count += 1
The condition is count < 5
. We can see that we start with the count
equal to 0 and increment it each time we execute the loop. Once the count
becomes 5, the loop stops executing.
❯ python3 main.py
0
1
2
3
4
For loops
A for
loop is a control structure used to iterate over a sequence (such as a list, tuple, string, or range) and execute a block of code for each element in the sequence. It's particularly useful when we know the number of iterations we want to perform or when we want to process each item in a collection.
The basic structure of a for
loop is as follows.
for element in sequence:
# Code to be executed
The loop iterates over each element
in the sequence
, and for each iteration, the specified block of code is executed.
for
loops are also often used with the range(...) function, which generates a sequence of numbers that we can iterate over:
for i in range(5):
print(i)
The following example prints integers in sequence from 0 to 5.
❯ python3 main.py
0
1
2
3
4
for
loops are very useful when iterating over elements of complex types, such as lists.
💡 A list is a built-in data structure that allows you to store and organize a collection of items.
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
In this example, the loop iterates through the fruits
list and prints each fruit on a separate line. The output is:
❯ python3 main.py
apple
banana
cherry
Knowing the loop mechanism in Python, we can easily improve our script that printed the "Hi, PyCharm" message three times. We will use a while
loop to repeat a block of code and a variable to track the number of times the loop is executed.
def print_hi(name):
greetings = f'Hi, {name}'
count = 3
while count > 0:
print(greetings)
count -= 1
if __name__ == '__main__':
print_hi('PyCharm')
We've introduced counter
to track the number of times the loop is executed. Initially, it is set to 3, and with each loop is it decreased by one using the -=
operator. The loop is executed as long as the count > 0
condition is True
. Once count
becomes 0, loop execution stops.
When we run the script, it prints the "Hi, PyCharm" message three times as before.
❯ python3 main.py
Hi, PyCharm
Hi, PyCharm
Hi, PyCharm
Now if we wanted to print the message more times, 10 for instance, we don't have to copy the code but just update the counter
value.
def print_hi(name):
greetings = f'Hi, {name}'
count = 10
while count > 0:
print(greetings)
count -= 1
The message is printed 10 times now.
❯ python3 main.py
Hi, PyCharm
Hi, PyCharm
Hi, PyCharm
Hi, PyCharm
Hi, PyCharm
Hi, PyCharm
Hi, PyCharm
Hi, PyCharm
Hi, PyCharm
Hi, PyCharm
Since we know the number of times the loop is executed, the while
loop can be easily transformed into a for
loop.
def print_hi(name):
greetings = f'Hi, {name}'
for _ in range(10):
print(greetings)
💡 Underscore (_) means the variable is irrelevant in this context, so we ignore it.
Conditional statements
Conditional statements are used to control the execution of our code based on certain conditions. They allow us to create branches in our code, ensuring that different blocks of code are executed depending on whether a condition is True
or False
.
The basic structure of a if
condition is as follows.
if condition:
# Code to be executed
The specified block of code is executed only if a condition is True
. Let's run a simple example.
count = 3
if count > 2:
print("Count is greater than 2")
print("Hello!")
We have a count
variable set to 3. Therefore, the count > 2
condition is fulfilled. As a result "Count is greater than 2" is printed.
❯ python3 main.py
Count is greater than 2
Hello!
When we set the count
variable to 2, the condition is not fulfilled.
count = 2
if count > 2:
print("Count is greater than 2")
print("Hello!")
When we run the script, we can quickly notice that the block of code under the if
statement isn't executed.
❯ python3 main.py
Hello!
We can create a more sophisticated execution flow using the else
statement.
if condition:
# some code
else:
# code to be executed if the condition is not met
The else
statement is executed when the previous if
condition isn't fulfilled. Let’s observe it in the following example.
count = 2
if count > 2:
print("Count is greater than 2")
else:
print("Count isn't greater than 2")
print("Hello!")
And execute it.
❯ python3 main.py
Count isn't greater than 2
Hello!
As the count
variable is set to 2, the count > 2
condition is not met, so the else
branch is executed.
If the if-else
statement is not enough, Python allows to create even more complex execution flow. The elif
statement allows us to check multiple conditions if the initial if
condition is not met.
if condition1:
# some code
elif condition2:
# some code
elif condition3:
# some code
else:
# code to be executed if conditions are not met
In this situation, the else
statement is used to execute a block of code if none of the previous conditions (in if
and elif
statements) are fulfilled.
count = 1
if count > 2:
print("Count is greater than 2")
elif count == 1:
print("Count equals 1")
else:
print("Count isn't greater than 2")
print("Hello!")
In the above example, we have the count == 1
condition. Since count
is equal to 1, the first condition is not met, and the execution falls into the second one. Here is the result of running the script.
❯ python3 main.py
Count equals 1
Hello!
Keep in mind that we can use elif
multiple times in case of more demanding logic.
Now let's slightly modify our greetings script to print "Hello, PyCharm" every second time.
First of all, we rename the greetings
variable to hiGreetings
.
hiGreetings = f'Hi, {name}'
We introduce another variable called helloGreetings
.
helloGreetings = f'Hello, {name}'
It will hold the new welcome text. Next, we add if
statement into the while
loop.
if (count % 2) == 0:
print(hiGreetings)
else:
print(helloGreetings)
We use (count % 2) == 0
as the condition. When running the loop, we will get the following values:
count
values: 10, 9, 7, 6, 5, 4, 3, 2, 1, andcount % 2
values: 0, 1, 0, 1, 0, 1, 0, 1, 0, 1.
When count
modulo 2 equals 0, we print "Hi, PyCharm". Otherwise, we print "Hello, PyCharm".
Here is the full code snippet.
def print_hi(name):
hiGreetings = f'Hi, {name}'
helloGreetings = f'Hello, {name}'
count = 10
while count > 0:
if (count % 2) == 0:
print(hiGreetings)
else:
print(helloGreetings)
count -= 1
if __name__ == '__main__':
print_hi('PyCharm')
Let's run the script and see the result.
❯ python3 main.py
Hi, PyCharm
Hello, PyCharm
Hi, PyCharm
Hello, PyCharm
Hi, PyCharm
Hello, PyCharm
Hi, PyCharm
Hello, PyCharm
Hi, PyCharm
Hello, PyCharm
Works like a charm!
Controlling the execution of the loop
In the case of for
loop, the number of times it repeats is derived from the sequences it iterates over and is known upfront. In the case of while
loop, we don’t know the number of times it repeats, so we provide a kind of “stop” condition explicitly. These are the default mechanisms to control loops' repetition. However in some particular cases, they are not enough, and more fine-grained means are needed. Python provides continue
, break
and else
keywords in addition to the default loop control flow.
continue statement
The continue
statement is used within loops to skip the rest of the current iteration and move on to the next iteration. When the continue
statement is encountered, the code block below it for the current iteration is skipped, and the loop proceeds with the next iteration.
Here's the basic structure of using the continue
statement within a loop:
for item in sequence:
if condition:
# code to be executed if the condition is met
continue
# code to be executed for other cases
or
while condition:
if condition:
# code to be executed if the condition is met
continue
# code to be executed for other cases
Let's look at examples.
for num in range(5):
if num == 3:
print("Skipping number 3")
continue
print("Number:", num)
In this example, when the loop encounters the number 3, it prints "Skipping number 3" and moves on to the next iteration without executing the subsequent line that prints the number itself.
❯ python3 main.py
Number: 0
Number: 1
Number: 2
Skipping number 3
Number: 4
A similar effect can be achieved using while
loop.
num = 0
while num < 5:
if num == 3:
print("Skipping number 3")
num += 1
continue
print("Number:", num)
num += 1
The major difference here when compared to the previous example is the fact num
is incremented in two places. Without the incrementation in the if
block, the code would fall into an infinite loop.
break statement
The break
statement is used within loops to abruptly terminate the loop's execution, regardless of whether the loop's condition or iterations are completed. When the break
statement is encountered, the program exits the loop immediately and continues with the code that follows the loop.
Here's the basic structure of using the break
statement within a loop:
for item in sequence:
if condition:
# code to be executed if the condition is met
break
# code to be executed for other cases
or
while condition:
if condition:
# code to be executed if the condition is met
break
# code to be executed for other cases
Let's see an example.
for num in range(5):
if num == 3:
print("Breaking at number 3")
break
print("Number:", num)
In this example, when the loop encounters the number 3, it prints "Breaking at number 3" and immediately exits the loop, without continuing with the rest of the iterations.
❯ python3 main.py
Number: 0
Number: 1
Number: 2
Breaking at number 3
Yet similar behavior can be achieved in the case of a while
loop, let's see an example.
num = 0
while (True):
if num == 3:
print("Breaking at number 3")
break
print("Number:", num)
num += 1
Here we have an interesting fact, we use a True
as the condition in the while
loop. If we hadn't used a break
statement, the loop would have run infinitely.
❯ python3 main.py
Number: 0
Number: 1
Number: 2
Breaking at number 3
The output is of course the same as in the previous example.
else clause
The else
clause in Python loops is used to specify a block of code that should be executed after the loop has completed its normal iterations. This code block is executed only if the loop completes its iterations without any break
statement being encountered. It is optional to use the else
clause with loops, but it can be useful in certain scenarios.
Here's the general structure of using the else
clause with loops:
for item in sequence:
# code to be executed for each item
else:
# code to be executed after the loop completes (optional)
or
while condition:
# code to be executed while the condition is true
else:
# code to be executed after the loop completes (optional)
Let's see an example.
for num in range(5):
if num == 3:
print("Number 3 found!")
break
else:
print("Number 3 not found.")
In this example, the loop iterates through the range. If the loop encounters the number 3, it prints "Number 3 found!" and exits the loop using the break
statement. If the loop completes all iterations without encountering the number 3, the else
block gets executed, printing "Number 3 not found."
❯ python3 main.py
Number 3 found!
In the range from 0 to 4, number 3 has been found. Now, we slightly modify the script and shorten the range.
for num in range(2):
if num == 3:
print("Number 3 found!")
break
else:
print("Number 3 not found.")
And of course, run it.
❯ python3 main.py
Number 3 not found.
Obviously, number 3 hasn't been found in the range from 0 to 2.
Summary
In this post, we learned the basics of flow control which are loops and conditional statements.
If
statements are crucial for implementing conditional logic, allowing your program to make decisions and take different actions based on various conditions.
Loops are essential for automating repetitive tasks, iterating through data, and solving various programming challenges. A for
loop is used to iterate over a sequence of items, while a while
loop is used to repeatedly execute a block of code as long as a specified condition is true.
Additionally, we can modify the loop flow using dedicated keywords. The continue
statement is helpful when you want to exclude certain elements or cases from being processed within a loop while continuing with the remaining iterations. The break
statement is useful when you want to prematurely exit a loop based on a certain condition. It’s particularly handy for stopping further iterations once a specific goal or condition is achieved. Using the else
clause with loops can be particularly useful when you want to perform some actions if a certain condition is not met during the loop’s execution. It can help improve the readability and logic flow of your code.