In Python, control statements serve to modify the execution flow within a program. They facilitate decision-making, enable the repetition of actions, or allow for the omission of specific sections of code depending on predefined conditions.
In Python , there are mainly three types of Control Statements:
- Conditional Statements
- Loop Statements
- Jump Statements
Conditional Statements
True to their name, conditional statements—often referred to as decision-making statements—are employed to facilitate decision-making within code. These statements assess a Boolean expression and dictate the progression of the program depending on the outcome of the specified condition.
In Python, there are mainly three categories of decision-making constructs: if, if…else, and if…elif…else.
1) if Statement
The if statement allows us to evaluate whether a particular condition holds true. If the defined condition resolves to True, the corresponding block of code is executed.
Let us see an example of Python if statement.
Example
# simple example of python if
x = 10
# if statement
if x > 5:
# inside if block
print("x is greater than 5")
Output:
x is greater than 5
Explanation:
In the preceding example, a variable named x is set to the value of 10. We employed the if conditional statement to determine whether the value of x exceeds 5 (x > 5). Within the if block, we have outputted a specific statement.
Given that the condition x > 5 evaluates to True, specifically 10 > 5, the code contained within the if-block will be executed, resulting in the designated statement being printed.
2) if…else Statement
The if-else construct serves as an enhancement to the fundamental if statement. Within the if-else framework, an alternate code block is triggered when the specified condition evaluates to false. This approach allows us to guarantee that one of the two potential actions is consistently performed based on the outcome of the condition.
Let us examine the subsequent illustration of a Python if…else statement.
Example
# simple example of python if-else
x = 3
# if-else statement
if x > 5:
# inside if block
print("x is greater than 5")
else:
# inside else block
print("x is less than or equal to 5")
Output:
x is less than or equal to 5
Explanation:
In the preceding example, a variable named x is set to the value of 3. We have employed the if-else conditional structure to evaluate whether the value of x exceeds 5 (x > 5). Within the if block, a specific statement is printed. Correspondingly, in the else block, we have included an alternative statement to be executed.
Given that the condition x > 5 evaluates to False—meaning that 3 is indeed not greater than 5—the code contained within the else-block is executed, resulting in the designated statement being printed.
3) if…elif…else Statement
The if-elif-else construct enables the evaluation of several conditions in a sequential manner. Each condition is assessed in order; when a condition evaluates to true, the associated block of code is executed, causing any subsequent conditions to be disregarded. The else block is executed solely in the scenario where all preceding conditions evaluate to false.
Let us now examine an illustration of the if…elif…else conditional statement in Python.
Example
# simple example of python if-elif-else
x = 5
# if-elif-else statement
if x < 5:
# inside if block
print("x is less than 5")
elif x > 5:
# inside elif block
print("x is greater than 5")
else:
# inside else block
print("x is equal to 5")
Output:
x is equal to 5
Explanation:
In the preceding illustration, a variable named x is set with an initial value of 5. We employed the if-elif-else conditional structure to determine whether the value of x is less than, greater than, or equal to 5. Within the if section, a specific statement is printed. Likewise, additional statements are included for execution in the elif and else sections.
Given that the condition x < 5 and x > 5 evaluates to False, the instructions contained within the if and elif sections are bypassed, resulting in the execution of the statement from the else section.
Loop Statements
Loop statements are constructs utilized for executing a series of instructions repeatedly based on a specified condition. These constructs enable the automation of tasks that require repetition, such as tallying, data manipulation, or evaluating conditions.
Utilizing loops allows us to avoid the repetition of identical code, resulting in a cleaner and more maintainable program.
In Python, there are two categories of loops: the for loop and the while loop.
1) for Loop
In Python, the for loop is utilized to traverse through a specified sequence, which can include structures such as lists, tuples, strings, or ranges. This construct enables the repetition of a code segment for every individual element present in the sequence.
Here is an example of Python for.
Example
# simple example of python for
beverages = ['tea', 'coffee', 'water', 'juice', 'milk']
# iterating over the list using for loop
for beverage in beverages:
print(beverage)
Output:
tea
coffee
water
juice
milk
Explanation:
In this illustration, we have a collection that contains several items. We employed a for loop to traverse through the elements of the specified collection and outputted them. Consequently, each item is displayed sequentially.
2) while Loop
The Python while loop allows for the continuous execution of a specific block of code as long as a specified condition evaluates to True. This construct is particularly advantageous when the total number of iterations cannot be determined in advance.
We will now see an example of Python while.
Example
# simple example of python while
# initializing counter
count = 1
# looping with while loop
while count <= 5:
# inside while loop
print(count, "Example")
# incrementing by 1
count += 1
Output:
1 C# Tutorial
2 C# Tutorial
3 C# Tutorial
4 C# Tutorial
5 C# Tutorial
Explanation:
In this example, we have set up a variable with an initial value of 5 and established a while loop that runs a segment of code as long as the variable remains less than or equal to 5. Within this block of code, there is a print statement, and the variable's value is increased by 1 with each iteration.
Consequently, we have entered the while loop since the condition evaluates to true. During each cycle of the loop, a message is displayed, and the value of the variable is increased by 1. When the counter hits 6, the condition counter <= 5 turns False, leading to the termination of the loop.
Jump Statements
Jump statements, commonly referred to as loop control statements, facilitate the rerouting of program execution to designated statements. In essence, these statements allow for the control of execution to be shifted to different sections of the program. In Python, there are three primary categories of jump statements: break, continue, and pass.
1) break Statement
The break statement allows us to terminate a loop instantly, regardless of whether the loop's condition has been completely satisfied. Upon invoking break, the control exits the loop and proceeds to the subsequent code that follows it. This is typically utilized when we have located the desired item or when it is unnecessary to continue iterating through the loop.
Let us see an example of Python break.
Example
# simple example of python break
# using for loop
for number in range(1, 10):
# checking if the current number is 6
if number == 6:
print("Found it!")
# using break to terminate the loop
break
print(f"Checking {number}")
Output:
Checking 1
Checking 2
Checking 3
Checking 4
Checking 5
Found it!
Explanation:
In the preceding example, we utilized a for loop to traverse through a sequence of numbers within a specified range. Within this loop, a condition was implemented that evaluates whether the number during the current iteration is equivalent to 6, and the break statement was employed to halt any subsequent iterations.
Consequently, the values are processed within the specified range. The loop concludes when the value reaches 6, at which point the break statement is executed.
2) continue Statement
The continue statement in Python enables us to bypass the current iteration of a loop and proceed directly to the subsequent one. It is commonly utilized when we aim to disregard particular instances within a loop without halting the entire loop's operation. This feature allows for more refined control over the flow by skipping only the unnecessary portions.
Example
# simple example of python continue
names = ['John', '', 'Michael', 'Sachin', '', '', 'Irfan']
# using for loop
for name in names:
# if there is an empty string in the list
if name == "":
# using the continue statement to skip the current iteration
continue
print(f"Hello, {name}!")
Output:
Hello, John!
Hello, Michael!
Hello, Sachin!
Hello, Irfan!
Explanation:
In this scenario, we have a collection that includes various names along with some empty strings. We utilize a for loop to traverse through this collection. Additionally, we employ the continue statement to bypass the ongoing iteration whenever the current element in the list is an empty string.
Consequently, the entries that contain empty strings are disregarded, and the names from the collection are displayed.
3) pass Statement
We can utilize the pass statement to create placeholder code. When executed, it performs no action; nevertheless, it serves the purpose of establishing a syntactically valid block that we intend to complete at a later time. The pass statement in Python is commonly employed when defining a loop, function, or conditional statement where the logic has not yet been implemented.
Let us see a simple example of Python pass.
Example
# simple example of python pass
# using for loop
for i in range(1, 6):
if i == 3:
# using pass keyword
pass
else:
print(i)
Output:
1
2
4
5
Explanation:
In the preceding example, a for loop has been utilized to traverse a defined range. Within this loop, the pass statement serves as a placeholder within the if-else construct.
Conclusion
In this tutorial, we explored control statements in Python utilizing various examples. We noted that Python primarily features three categories of control statements: decision-making statements, looping statements, and jump statements.
Decision-making constructs assist us in making choices within our code. These constructs encompass if, if-else, and if-elif-else statements. In contrast, looping constructs enable us to execute a block of code multiple times, utilizing for and while loops. Additionally, jump statements such as break, continue, and pass facilitate the transfer of control within the program to specific statements.
Control Statements in Python FAQs
1. What are control statements in Python?
Control statements govern the execution sequence of a program. They are essential for making decisions (such as using if and if-else), creating loops (through for and while), and modifying the behavior of loops (with commands like break, continue, and pass).
2. What is the difference between if, elif, and else?
- if: Checks the first condition.
- elif: Checks additional conditions if the previous ones were false.
- else: Executes when all previous conditions are false.
- for: Used when you know how many times to iterate (e.g., over a list or range).
- while: Used when you want to loop until a condition becomes false.
3. What is the difference between for and while loops?
4. What does the break statement do?
It promptly terminates the closest loop (which can be either a for loop or a while loop), regardless of whether the loop's condition remains satisfied.
5. What does the continue statement do?
It bypasses the ongoing iteration and proceeds to the subsequent one in the loop, omitting the execution of any remaining code within the current cycle of the loop.