Sitemap

Beginners Guide: Python Control Flow

6 min readNov 8, 2023

--

Python, a versatile programming language, frequently requires programs to navigate through particular statements, repeat sequences of statements, or select between distinct sets of statements based on specific conditions. Control flow is helpful in this situation. Control flow, such as conditionals, are critical tools for controlling the order in which statements in a Python program are performed. It is the programming concept that determines how statements and instructions are executed in a program. It acts as a navigational framework, guiding the execution route of your code. Control flow helps your program to make decisions, branch, and iterate over data sequences. To design dynamic and responsive programs that adapt to diverse circumstances, the use of conditional statements and loops is essential.

Code Example: A conditional is used in this example to determine whether the value of x is greater than 5.

# Calculate 'i' as the result of 100 divided by 25
i = (100/25)

# Check if 'i' is greater than 5 and print the appropriate message
if i > 5:
print("i is greater than 5")
else:
print("i is not greater than 5")

Output

i is not greater than 5

NOTE: Python's control flow is important for several reasons, but most importantly aids Adaptability and Readability.

Understanding Conditional Statements: if, elif, else

Conditional statements are a fundamental concept in programming. They allow the computer to execute different actions based on certain conditions. The most common conditional statements are "if", "elif", and "else". The "if" statement executes a code block if a specific condition is true. The "elif" statement is short for "else if", allowing you to check for multiple conditions, executing a block of code for each true one. Finally, the "else" statement is executed if none of the previous conditions were true. It is important to understand how these statements work to create more complex programs.

  1. if statement: The "if" statement is a conditional statement that allows you to execute a specific block of code only if a certain condition is true. If the condition is not met, then the code block is skipped. The basic syntax of an "if" statement in Python is as follows:
If condition:
# code block to be executed if the condition is true

Here, "condition" is the expression that is evaluated to be either True or False. If the condition evaluates to True, the code block following the if statement is executed. If it evaluates to False, the code block is skipped, and the program moves on to the following line of code after the block.

For example, the following code uses an "if" statement to check if a variable "x" is less than the variable "y"

# Define two variables 'x' and 'y' and set their values
x = 2
y = 8

# Check if 'x' is less than 'y'
if x < y:
# If 'x' is indeed less than 'y', print 'yes'
print('x is less than y')

Output

x is less than y

2. if-else statement: The if statement, as previously mentioned, runs the code block when the condition is true. When the declared if condition is untrue, the else statement compares to the if statement to run a code block. The basic syntax of an "if-else" statement in Python is as follows:

if condition:
# code block to be executed if condition is true
else:
# code block to be executed if condition is false

For example, the following code uses an "if-else" statement to check if a variable "x" is less than the variable "y" and prints a message accordingly:

# Define two variables 'x' and 'y' and set their values
x = 24
y = 8

# Checks if 'x' is less than 'y'
if x < y:
print('x is less than y')
else:
print('x is greater than to y')

Output:

x is greater than to y

In this example, since the condition "x < y" is false, the code block following the "else" statement is executed, and the message "x is greater than or equal to y" is printed.

Get Godsfavour Chukwudi’s stories in your inbox

Join Medium for free to get updates from this writer.

3. if-elif-else ladders: The elif statement allows the checking of numerous conditions in a row and runs various code blocks based on which condition is true. The elif statement is optional, comparable to the else statement. Nonetheless, unlike the else statement, numerous elif statements can follow an if statement in a code block. The basic syntax of an "if-elif-else" ladder in Python is as follows:

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

In this syntax, the program checks for multiple conditions in a row. If `condition1` is true, the code block following it is executed. If `condition1` is false and `condition2` is true, the code block following `condition2` is executed. This process continues for each `elif` statement until one of the conditions is true. If none of the conditions are true, the code block following `else` is executed.

For example, the following code uses an "if-elif-else" statement to check if a number is positive, negative, or zero:

num = -5
if num > 0:
print("The number is positive")
elif num == 0:
print("The number is zero")
else:
print("The number is negative")

Output:

The number is negative

In this example, since `num` is less than zero, the code block following the `else` statement is executed, and the message “The number is negative” is printed.

Nested Conditionals: Nested conditionals in Python refer to placing conditional statements (if, elif, or else) inside other conditional statements. This hierarchical structure allows for the evaluation of multiple conditions and the execution of different code blocks based on the fulfilment of these conditions. Nested conditionals are valuable for handling complex decision-making scenarios where multiple conditions must be considered. They provide a way to structure and organise code to handle various possibilities and make choices based on them.

It takes the syntax:

if condition_1:
if condition_1_a:
...
elif condition_1_b:
...
else:
...
elif condition_2:
if condition_2_a:
...
else:
...
elif condition_3:
if condition_3_a:
...
else:
...

Here's what the code might look like:

num = 12
if num > 10:
if num % 2 == 0:
print("The number is greater than 10 and even.")
else:
print("The number is greater than 10 but odd.")
else: print("The number is not greater than 10.")

In this example, we first check whether `num` is greater than 10 using an `if` statement. If that condition is true, we check whether `num` is even by using another `if` statement nested inside the first one. If that condition is also true, then we print a message indicating that the number is greater than ten and even. If `num` is not even, we print a message indicating that the number is greater than ten but odd. If the first `if` statement is false, we print a message indicating that the number is not greater than 10.

Output:

The number is greater than 10 and even.

As you can see, nested conditionals can create more complex decision-making structures in a program. However, it's important to use them judiciously, as too many nested conditionals can make code harder to understand and debug.

REFERENCE:

Online, S. (2023, October 3). Conditional Statements in Python &#8211; Python Tutorial — Shiksha Online. Shiksha.com. https://www.shiksha.com/online-courses/articles/conditional-statement-in-python/

Conditionals in Python — Data Science Discovery. (n.d.). Data Science Discovery. https://discovery.cs.illinois.edu/learn/Simulation-and-Distributions/Conditionals-in-Python/

Jeremiah, O. (2023, March 7). How to Use Conditional Statements in Python — Examples of if, else, and elif. freeCodeCamp.org. https://www.freecodecamp.org/news/how-to-use-conditional-statements-if-else-elif-in-python/#:~:text=Conditional%20statements%20are%20an%20essential,to%20use%20them%20in%20practice.

Python, R. (2023, September 7). Conditional Statements in Python. https://realpython.com/python-conditional-statements/

Control flow. (2022, December 31). https://www.computerhope.com/jargon/c/contflow.html

Python If Elif Else (With Examples). (2023, August 21). Wiingy. https://wiingy.com/learn/python/python-if-elif-else/

--

--