One of the essential concepts in Python is control flow. Control flow refers to the order in which statements and instructions are executed in a program. Python provides several control flow structures that enable developers to create powerful and flexible programs.
In this blog post, we will discuss the various control flow structures in Python and how they can be used in different scenarios.
if/else Statements
If/else statements are used to make decisions based on a condition. The basic syntax of an if statement is as follows:
if condition:
#code to execute if condition is True
else:
#code to execute if condition is False
Here, the condition is a Boolean expression that evaluates to either True or False. If the condition is True, the code inside the if block is executed, and if the condition is False, the code inside the else block is executed.
For example, let’s say we want to print “Even” if a given number is even, and “Odd” if it is odd. We can use an if/else statement to achieve this as shown below:
num = 4
if num % 2 == 0:
print("Even")
else:
print("Odd")
Loops
Loops are used to execute a block of code repeatedly. Python provides two types of loops: for loops and while loops.
for
For loops are used to iterate over a sequence of elements such as a list, tuple, or string. The basic syntax of a for loop is as follows:
for element in sequence:
#code to execute for each element in the sequence
Here, element is a variable that represents each element in the sequence, and sequence is the sequence of elements to iterate over. For example, let’s say we want to print each element in a list:
my_list = [1, 2, 3, 4, 5]
for element in my_list:
print(element)
Looping over multiple lists
Sometimes we need to iterate over multiple lists at the same time. We can use the zip() function to combine two or more lists, and then use a for loop to iterate over the combined lists.
names = ["Tina", "Virat", "Rohit"]
ages = [25, 30, 35]
genders = ["Female", "Male", "Other"]
for name, age, gender in zip(names, ages, genders):
print(f"{name} is {age} years old and identifies as {gender}.")
In this example, we use the zip() function to combine three lists: names, ages, and genders. We then use a for loop to iterate over the combined lists and print a sentence for each person in the list.
while
While loops are used to execute a block of code repeatedly as long as a condition is True. The basic syntax of a while loop is as follows:
while condition:
#code to execute as long as condition is True
Here, the condition is a Boolean expression that is evaluated before each iteration of the loop. The loop continues to execute as long as the condition is True. For example, let’s say we want to print the numbers from 1 to 5 using a while loop:
num = 1
while num <= 5:
print(num)
num += 1
Break and Continue Statements
The break and continue statements are used to modify the behavior of loops.
Break Statement
The break statement is used to exit a loop prematurely. When the break statement is encountered inside a loop, the loop is immediately terminated, and the control is transferred to the next statement after the loop. For example, let’s say we want to print the numbers from 1 to 5, but stop the loop when we encounter the number 3:
for num in range(1, 6):
if num == 3:
break
print(num)
Continue
The continue statement is used to skip over a certain iteration in a loop and move on to the next iteration. It is useful when we want to skip certain elements in a loop or when we want to avoid executing certain statements in a loop based on a condition.
The basic syntax of the continue statement is as follows:
while condition:
# statements
if condition:
continue
# statements
Here, the continue statement is used inside a loop (while or for loop). When the condition inside the loop is True, the statements inside the loop are executed. If the condition inside the if statement is also True, then the continue statement is executed, and the loop skips to the next iteration without executing the statements below the continue statement.
Let’s see an example of how the continue statement works:
my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
for num in my_list:
if num % 2 == 0:
continue
print(num)
In this example, we have a list of numbers from 1 to 10. We use a for loop to iterate over each number in the list. If the number is even (i.e., divisible by 2), the continue statement is executed, and the loop skips to the next iteration. If the number is odd, the print statement is executed, and the number is printed to the console.
Suppose we have a list of numbers, and we want to calculate the sum of all even numbers in the list. We also want to skip any numbers that are greater than 10. Here’s one way we can achieve this using control flow structures:
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
sum_of_evens = 0
for num in numbers:
if num > 10:
continue
elif num % 2 == 0:
sum_of_evens += num
print(sum_of_evens)
In this example, we use a for loop to iterate over each number in the list. Inside the loop, we first check if the number is greater than 10. If it is, we use the continue statement to skip over that number and move on to the next iteration.
If the number is not greater than 10, we then check if it is even by using the modulus operator (%). If the number is even, we add it to the variable sum_of_evens.
After the loop is finished iterating over all the numbers in the list, we print the sum_of_evens
variable to the console.
Nested Loops
Python allows us to use loops inside other loops. This is known as nested loops. Nested loops are used when we need to iterate over a sequence of elements inside another sequence. For example, let’s say we have a list of lists, and we want to iterate over each element in the inner lists:
my_list = [[1, 2], [3, 4], [5, 6]]
for inner_list in my_list:
for element in inner_list:
print(element)
Try/Except Statements
Try/except statements are used to handle exceptions in Python. Exceptions are errors that occur during the execution of a program. When an exception is raised, the program stops executing and displays an error message. Try/except statements allow us to catch and handle these exceptions, so the program can continue running.
The basic syntax of a try/except statement is as follows:
try:
#code that may raise an exception
except ExceptionType:
#code to handle the exception
Here, ExceptionType is the type of exception that we want to handle. For example, let’s say we want to handle the exception that occurs when we try to divide a number by zero:
num1 = 5
num2 = 0
try:
result = num1 / num2
except ZeroDivisionError:
print("Cannot divide by zero")
Pass Statement
The pass statement is used when we need to create a placeholder for code that we haven’t written yet. It does nothing and is used to avoid syntax errors. For example, let’s say we want to define a function but haven’t decided what it will do yet:
def my_function():
pass
Here, we use the pass statement to create a placeholder for the code that we will write later.