✨Flow Control

In this section, we will discuss various aspects of Python flow control, including conditional statements, loops, and function calls. We will explore how to use these tools to control the flow of ...

Python Flow Control refers to the order in which the code is executed in a program. It is used to control the execution of statements and allows the program to execute different code blocks based on certain conditions. In Python, flow control is achieved using conditional statements, loops, and function calls. Understanding flow control is essential for writing efficient and effective programs.

1. Python if...else Statement

The if...else statement is one of the most commonly used control structures in Python. It allows you to execute a block of code based on a condition. The condition is evaluated to either True or False, and the code block is executed only if the condition is True. If the condition is False, the code block is skipped or another block of code is executed instead. This provides a way to control the flow of execution in a Python program.

In Python, there are three forms of the if...else statement.

  1. if statement

  2. if...else statement

  3. if...elif...else statement

a. Python if statement

In Python, the if statement is used to perform a certain action only when a certain condition is true. It allows us to control the flow of the program based on the evaluation of an expression that returns a Boolean value (True or False). If the expression is true, then the code inside the if block will be executed, otherwise, the code inside the if block will be skipped.

Here's the general syntax of the if statement:

if expression:
    statement(s)

The expression is a condition that is evaluated and returns a Boolean value (True or False). The statement(s) that follow the if block are executed only if the expression is evaluated to True.

For example, let's say we want to print a message if a number is greater than 5. We can use the if statement as follows:

num = 8

if num > 5:
    print("The number is greater than 5")

In this example, if the value of the variable num is greater than 5, then the message "The number is greater than 5" will be printed. Otherwise, nothing will be printed.

b. Python if...else Statement

The if...else statement in Python allows you to execute a block of code if a certain condition is met and a different block of code if that condition is not met. It is a fundamental part of programming and can be used to make decisions and control the flow of your program.

The basic syntax for the if...else statement in Python is as follows:

if condition:
    # code to be executed if condition is True
else:
    # code to be executed if condition is False

In this statement, the condition is evaluated as either True or False. If it is True, the block of code indented under the if statement is executed. If it is False, the block of code indented under the else statement is executed instead.

The if...else statement evaluates the given condition:

  • the code inside if is executed

  • the code inside else is skipped

If the condition evaluates to False,

  • the code inside else is executed

  • the code inside if is skipped

Here's an example of a Python if...else statement:

num = int(input("Enter a number: "))
if num % 2 == 0:
    print(num, "is even")
else:
    print(num, "is odd")

In this example, the user is prompted to enter a number. The number is then checked to see if it's even or odd using the modulus operator (%). If the number is even (i.e., its remainder when divided by 2 is 0), the program prints a message saying so. Otherwise, it prints a message saying the number is odd. The if statement is followed by the else statement, which is executed if the condition in the if statement is False.

c. Python if...elif...else Statement

The Python if...elif...else statement is used when we need to test multiple conditions, and execute a different block of code depending on which condition is true. The elif stands for "else if", and allows us to check additional conditions if the first condition is not met. The else statement is executed if none of the if or elif conditions are true.

The basic syntax of the if...elif...else statement in Python is:

if condition1:
    # code to execute if condition1 is true
elif condition2:
    # code to execute if condition2 is true
elif condition3:
    # code to execute if condition3 is true
else:
    # code to execute if none of the conditions are true

Note that you can have any number of elif statements, depending on how many conditions you need to check. Also note that the else statement is optional.

Here is an Example Python if...elif...else Statement

number = 0

if number > 0:
    print("Positive number")

elif number == 0:
    print('Zero')
else:
    print('Negative number')

print('This statement is always executed')

Output

Zero
This statement is always executed

In the above example, we have created a variable named number with the value 0. Here, we have two condition expressions:

Here, both the conditions evaluate to False. Hence the statement inside the body of else is executed.

2. Python for Loop

In Python, a for loop is a control flow statement that is used to iterate over a sequence of elements. It allows you to execute a block of code repeatedly for a specific number of times or for each element in a sequence. The for loop is commonly used for tasks like iterating over a list, string, tuple, or range of numbers. In this section, we will explore the different ways you can use a for loop in Python.

The syntax of the for loop is:

for val in sequence:
    # statement(s)

Here, val accesses each item of sequence on each iteration. Loop continues until we reach the last item in the sequence.

a. Using a for Loop with a Sequence

In Python, the for loop is used to iterate over a sequence of elements. The sequence can be a string, a list, a tuple, or any other iterable object. The basic syntax for a for loop is as follows:

for element in sequence:
    # code block to be executed

The loop iterates through each element in the sequence and executes the code block. The loop continues until all the elements in the sequence have been processed.

Let's take a look at an example of using a for loop with a list of numbers:

numbers = [1, 2, 3, 4, 5]
for num in numbers:
    print(num)

In this example, the for loop iterates through each number in the list numbers and prints it to the console. The output would be:

1
2
3
4
5

The loop stops when it reaches the end of the list, which is after processing the number 5.

Note that the loop variable (num in this example) takes on the value of each element in the sequence in turn, and the code block is executed once for each value of the loop variable.

b. Using the range() Function in for Loops

The range() function in Python generates a sequence of numbers. It can be used in for loops to iterate a certain number of times.

The basic syntax of the range() function is:

range(start, stop, step)

Here,

  • start (optional) is the starting value of the sequence. The default value is 0.

  • stop is the ending value of the sequence (exclusive).

  • step (optional) is the difference between each number in the sequence. The default value is 1.

Let's see some examples of using range() in for loops.

  1. Printing the numbers from 0 to 9:

for i in range(10):
    print(i)
  1. Printing the even numbers from 0 to 10:

for i in range(0, 11, 2):
    print(i)
  1. Printing the numbers from 10 to 1:

for i in range(10, 0, -1):
    print(i)
  1. Summing up the numbers from 1 to 10:

total = 0
for i in range(1, 11):
    total += i
print(total)

These are just a few examples, but you can use the range() function in many different ways to generate the sequence of values that you need for your loop.

c. Nested for Loops

In Python, it is possible to have a for loop inside another for loop. This is called a nested for loop. The inner loop will be executed completely for each iteration of the outer loop.

The syntax for a nested for loop is as follows:

for outer_var in outer_sequence:
    # execute outer loop code here
    for inner_var in inner_sequence:
        # execute inner loop code here

Here, outer_sequence is the sequence for the outer loop and inner_sequence is the sequence for the inner loop.

Let's see an example of a nested for loop that prints out the multiplication table from 1 to 10:

for i in range(1, 11):
    for j in range(1, 11):
        print(i * j, end='\t')
    print()

In this example, the outer loop iterates over the numbers from 1 to 10, and for each iteration, the inner loop iterates over the numbers from 1 to 10 and prints out the product of i and j. The end='\t' argument in the print statement is used to separate the numbers with tabs instead of newlines. Finally, a new line is printed after each iteration of the inner loop to move to the next row of the multiplication table.

c. Using the break and continue Statements in for Loops

In Python, the break and continue statements can be used inside for loops to control the flow of execution.

The break statement is used to exit a loop early, regardless of whether the loop has finished iterating over all of its elements. When the break statement is encountered inside a loop, the loop is terminated immediately and program execution continues with the next statement after the loop.

The continue statement is used to skip to the next iteration of a loop, without executing any remaining statements in the current iteration. When the continue statement is encountered inside a loop, the loop immediately skips to the next iteration, without executing any remaining statements in the current iteration.

Let's see some examples of using break and continue in for loops.

Example 1: Using break statement

fruits = ["apple", "banana", "cherry", "kiwi", "orange"]
for fruit in fruits:
    if fruit == "cherry":
        break
    print(fruit)

Output:

apple
banana

In this example, the break statement is used to exit the loop when the variable fruit takes the value "cherry". The loop terminates at that point, and the remaining fruits "kiwi" and "orange" are not printed.

Example 2: Using continue statement

fruits = ["apple", "banana", "cherry", "kiwi", "orange"]
for fruit in fruits:
    if fruit == "cherry":
        continue
    print(fruit)

Output:

apple
banana
kiwi
orange

In this example, the continue statement is used to skip the "cherry" fruit, and the remaining fruits "apple", "banana", "kiwi", and "orange" are printed.

These are just some basic examples of how to use break and continue statements in for loops. Depending on the specific use case, you may need to use more complex logic in combination with these statements to achieve the desired behavior.

3. Python while Loop

A while loop in Python repeatedly executes a block of code as long as a certain condition is true. The loop continues until the condition becomes false.

The syntax of a while loop in Python is as follows:

while condition:
    # code to execute while condition is true

The code inside the while loop will keep executing as long as the condition is true. When the condition becomes false, the loop exits and control moves to the next statement after the while loop.

It's important to make sure that the condition inside the while loop will eventually become false, otherwise, the loop will run infinitely and the program will become unresponsive.

Here's an example of a while loop in Python:

# Using a while loop to print numbers 1 to 5
count = 1
while count <= 5:
    print(count)
    count += 1

This code will output:

1
2
3
4
5

In this example, the while loop is used to print the numbers 1 to 5. The loop starts with count variable initialized to 1. The loop continues to execute as long as the value of count is less than or equal to 5. Inside the loop, the value of count is printed to the console, and then count is incremented by 1 using the += operator. This process continues until the value of count is greater than 5, at which point the loop exits.

a. Using a while Loop with the break and continue Statements

In addition to the basic while loop structure, we can also use the break and continue statements to control the flow of the loop.

The break statement is used to exit a loop prematurely, regardless of the loop's condition. For example:

i = 0
while i < 5:
    print(i)
    if i == 3:
        break
    i += 1

Output:

0
1
2
3

In the example above, the break statement is used to exit the loop when i is equal to 3, so the loop only runs 4 times instead of 5.

On the other hand, the continue statement is used to skip over a specific iteration of the loop and move on to the next one. For example:

i = 0
while i < 5:
    i += 1
    if i == 3:
        continue
    print(i)

Output:

1
2
4
5

In the example above, the continue statement is used to skip over the iteration where i is equal to 3, so it is not printed in the output.

b. Using the else Statement with a while Loop

The else statement can also be used with a while loop in Python. It is executed when the loop condition becomes false. This means that the code inside the else block will be executed after the while loop has completed all of its iterations.

Here is an example:

i = 1
while i <= 5:
    print(i)
    i += 1
else:
    print("Loop is finished")

In this example, the while loop will iterate five times and print the values of i from 1 to 5. After the loop finishes, the else block will be executed and it will print the message "Loop is finished".

If the while loop is terminated prematurely by a break statement, the else block will not be executed.

Here's an example that demonstrates this:

i = 1
while i <= 5:
    if i == 3:
        break
    print(i)
    i += 1
else:
    print("Loop is finished")

In this example, the while loop will iterate three times and print the values of i from 1 to 2. When i becomes 3, the break statement is executed, which terminates the loop prematurely. Since the loop was terminated by a break statement, the else block is not executed.

4. Python break and continue

In Python, the break and continue statements are used to alter the normal flow of a loop.

  • The break statement is used to terminate the loop entirely and continue with the next statement after the loop.

  • The continue statement is used to skip the current iteration of the loop and move on to the next iteration.

a. Python break Statement

The break statement in Python is used to terminate the execution of a loop (for loop, while loop) prematurely. When a break statement is encountered inside a loop, the loop is exited and the control is transferred to the next statement following the loop.

Here's the basic syntax of a break statement:

while condition:
    # some code
    if some_condition:
        break
    # some more code

In the above example, the break statement is used to exit the while loop prematurely when the condition some_condition is satisfied.

Similarly, the break statement can also be used inside a for loop:

for variable in sequence:
    # some code
    if some_condition:
        break
    # some more code

In the above example, the break statement is used to exit the for loop prematurely when the condition some_condition is satisfied.

b. Python continue Statement

The continue statement is another flow control statement in Python that is used inside loops (for loop or while loop). It is used to skip over a part of the loop's code block for a specific condition and then continue with the next iteration of the loop.

When the continue statement is encountered inside the loop, the code execution jumps back to the beginning of the loop's code block and starts the next iteration, ignoring the remaining code in the current iteration.

Here is the syntax for the continue statement:

while/for condition:
    # code block
    if condition:
        continue
    # more code

As shown in the example above, the continue statement is usually used inside a conditional statement (if statement) to check for a specific condition. When the condition is met, the continue statement is executed, and the code inside the current iteration of the loop is skipped, and the next iteration starts.

4. Python pass Statement

The pass statement in Python is used as a placeholder where a statement is required syntactically, but no action is required. It is commonly used as a placeholder while writing code to indicate that some part of the code will be implemented later. The pass statement is a null operation, meaning it does nothing.

For example, if you are defining a function, and you have not yet written the body of the function, you can use the pass statement as a placeholder, so that the function definition is syntactically correct:

def my_function():
    pass

In this example, the function my_function() does not do anything, but the pass statement allows the function to be defined syntactically.

Another example is using pass in a loop when you want to do nothing for a certain condition:

for i in range(10):
    if i % 2 == 0:
        pass
    else:
        print(i)

In this example, the pass statement is used when i is an even number, so nothing is done. The else statement is only executed when i is an odd number, so i is printed.

a. Using pass With Conditional Statement

The pass statement in Python is a placeholder that does nothing. It is used to avoid syntax errors when a statement is required syntactically, but you don't want any command or code to execute.

When used with conditional statements, pass allows you to create a valid empty block of code. This can be useful when you are not yet sure what code to put inside the block.

Here's an example of using pass with a conditional statement:

x = 10

if x < 5:
    pass
else:
    print("x is greater than or equal to 5")

In this example, if the value of x is less than 5, the pass statement will be executed and the program will move on to the next line of code. If the value of x is greater than or equal to 5, the else block will be executed and the message "x is greater than or equal to 5" will be printed.

b. Use of pass Statement inside Function or Class

The pass statement is often used as a placeholder for a block of code that is not yet implemented, but needs to be added later. It is commonly used in situations where the syntax requires a statement, but no action is required.

In functions or classes, the pass statement can be used as a placeholder for the body of the function or class definition. This can be useful when you want to define the structure of the function or class, but have not yet written the code to implement it.

Here is an example of using the pass statement inside a function:

def my_function():
    pass

In this example, my_function() is defined with the pass statement as the function body. This function does nothing when called, but it can be useful as a placeholder for a function that will be defined later.

Similarly, the pass statement can be used inside a class definition:

class MyClass:
    pass

In this example, MyClass is defined with the pass statement as the class body. This class does nothing, but it can be useful as a placeholder for a class that will be defined later.

Last updated