Control Flow in Python

Control Flow in Python

This article explains control flow in Python.

YouTube Video

If Statement in Python

The if statement in Python is a syntax for conditional branching. It is used to execute a block of code if a specific condition evaluates to True (true).

Basic Syntax

The if statement in Python basically follows the structure below.

1x = 10
2
3if x > 5: # Check if the condition(x > 5) is True
4    # If the condition is True, execute this code block
5    print("x is greater than 5")

In this example, "x is greater than 5" is printed if the variable x is greater than 5.

else Statement

Using else after an if statement allows you to specify code to execute when the condition is false.

1x = 3
2
3if x > 5:
4    print("x is greater than 5")
5else:
6    print("x is less than or equal to 5")

In this example, the output will be "x is less than or equal to 5".

elif Statement

If you need to check multiple conditions, you can use elif, which stands for "else if".

1x = 5
2
3if x > 5:
4    print("x is greater than 5")
5elif x == 5:
6    print("x is equal to 5")
7else:
8    print("x is less than 5")

In this example, "x is equal to 5" is printed.

Notes

  • A colon (:) is required after if, elif, or else.
  • The block of code executed when a condition is true needs to be indented. In Python, the standard indentation is usually 4 spaces, but other numbers of spaces are fine as long as you are consistent.
  • You can use any expression that evaluates to a boolean value as a condition. This means you can use conditional expressions combined with comparison or logical operators.

Mastering Python's if statement allows you to control the program's execution flow flexibly.

Multiple Conditional Branching in Python

There are several ways to implement a switch-like functionality in Python, similar to that in other languages. In Python, it is common to use if-elif-else statements or dictionaries to create structures similar to a switch statement.

Method 1: if-elif-else Statement

The simplest way is to use the if-elif-else statement for conditional branching.

 1def switch_example(value):
 2    if value == 1:
 3        return "Value is one"
 4    elif value == 2:
 5        return "Value is two"
 6    elif value == 3:
 7        return "Value is three"
 8    else:
 9        return "Unknown value"
10
11print(switch_example(1))  # Output: Value is one
12print(switch_example(4))  # Output: Unknown value

Method 2: Using Dictionaries

By mapping functions or values to a dictionary, it's possible to create a structure similar to a switch statement. This is convenient when you want to perform different operations for specific values.

 1def case_one():
 2    return "Value is one"
 3
 4def case_two():
 5    return "Value is two"
 6
 7def case_default():
 8    return "Unknown value"
 9
10def switch_example(value):
11    switch_dict = {
12        1: case_one,
13        2: case_two
14    }
15
16    # Use get() method to retrieve the corresponding function from the dictionary
17    # If the value is not found in the dictionary, use case_default as a fallback
18    return switch_dict.get(value, case_default)()
19
20print(switch_example(1))  # Output: Value is one
21print(switch_example(3))  # Output: Unknown value

Method 3: match Statement (Python 3.10 and later)

The match statement was introduced in Python 3.10. It is a pattern matching syntax that provides functionality similar to a switch statement.

 1def switch_example(value):
 2    match value:
 3        case 1:
 4            return "Value is one"
 5        case 2:
 6            return "Value is two"
 7        case 3:
 8            return "Value is three"
 9        case _:
10            return "Unknown value"
11
12print(switch_example(1))  # Output: Value is one
13print(switch_example(4))  # Output: Unknown value

Summary

  • if-elif-else Statement: Simple and adaptable to many cases.
  • Dictionaries: Use mappings of functions or values to enable efficient branching.
  • match Statement: Allows more intuitive branching in Python 3.10 and later. Closest to a switch statement.

For Loops in Python

Python's for statement is used to iterate over each element of an iterable object such as a list, string, or dictionary. The basic syntax of a for statement is as follows:.

1# Loop through each item in the iterable
2for variable in iterable:
3    # Execute this block of code for each item in the iterable
4    code_to_execute

Here are some specific examples:.

Example Using a List

1fruits = ["apple", "banana", "cherry"]
2for fruit in fruits:
3    print(fruit)

This code calls the print function for each element in the list fruits, outputting the name of each fruit.

Example Using range()

The range() function generates integers within a specified range, making it useful for numeric iterations.

1for i in range(5):
2    print(i)

range(5) generates integers from 0 to 4. In this case, 0, 1, 2, 3, 4 will be output sequentially.

Example Using a Dictionary

In the case of dictionaries, keys are iterated by default, but you can also retrieve key-value pairs.

1person = {"name": "Alice", "age": 25}
2for key in person:
3    print(key, person[key])

Alternatively, use the items() method to simultaneously retrieve keys and values.

1person = {"name": "Alice", "age": 25}
2for key, value in person.items():
3    print(key, value)

Nested for Loop

It is also possible to nest for loops to perform complex iteration processes.

1matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
2for row in matrix:
3    for num in row:
4        print(num)

This code iterates through each row of the list matrix and sequentially outputs the numbers in each row.

continue to skip an iteration and break to terminate a loop

Using continue within a for loop will skip the current iteration and move to the next one. Additionally, using break will completely terminate the loop.

1for i in range(10):
2    if i == 5:
3        continue
4    if i == 8:
5        break
6    print(i)

In this example, the loop skips when i is 5 and terminates when i is 8. Thus, the output will be 0, 1, 2, 3, 4, 6, 7.

Python's for loop is highly flexible and can be used in a variety of scenarios. Depending on the type of iterative processing you want to perform, it can be used in combination with lists, dictionaries, strings, and range().

while Loop in Python

In Python, the while loop is a control structure used to repeatedly execute code within the block as long as the condition remains True. The basic syntax of the while loop is as follows:.

1while condition:
2    # This block of code will be executed repeatedly as long as the condition is true
3    statement1
4    statement2
5    ...

Example:

In the following example, a while loop is used to output the numbers from 1 to 5.

1i = 1
2while i <= 5:
3    print(i)
4    i += 1

This code works as follows.

  • Start with i as 1, print i while it is less than or equal to 5, and increment i by 1 each time.

Note:

You need to keep the following points in mind when using the while statement.

  1. Beware of infinite loops

    • If the condition in a while loop is always True, it will result in an infinite loop. Appropriate operations must be performed to change the condition; otherwise, the program will not stop.
  2. Using break and continue:

    • break is used when you want to exit the loop prematurely.
    • continue skips the current iteration and starts the next one. Be careful, as improper loop conditions can result in an infinite loop.

Example of break:

1i = 1
2while i <= 5:
3    if i == 3:
4        break  # Exit the loop when i becomes 3
5    print(i)
6    i += 1
  • In this case, after 1 and 2 are output, the loop ends when i becomes 3.

Example of continue:

1i = 0
2while i < 5:
3    i += 1
4    if i == 3:
5        # Skip the print statement and move to the next loop iteration when i is 3
6        continue
7    print(i)
  • In this case, output is skipped only for 3, resulting in 1, 2, 4, 5.
  • By incrementing the value of i at the beginning of the loop, the counter advances even if continue is executed, preventing an infinite loop.

You can follow along with the above article using Visual Studio Code on our YouTube channel. Please also check out the YouTube channel.

YouTube Video