Python Control Flow: if, else and while Statements

Learn how to use Python control flow with if, else and while statements to build dynamic programs. Master loops, break, continue and real-world applications.

Credit: Artturi Jalli | Unsplash

Control flow is a fundamental concept in programming that determines the order in which statements are executed. In Python, control flow structures enable you to make decisions, repeat tasks, and handle various conditions. The three most important control flow structures in Python are if statements, else statements, and while loops. Understanding these control structures is critical for writing efficient, dynamic, and flexible programs that respond to different conditions and perform repeated tasks.

The if statement is used to execute code only when a specified condition is true, while the else statement provides an alternative action when the condition is false. Together, if-else statements form the backbone of decision-making in Python. Meanwhile, while loops allow you to repeat a block of code as long as a certain condition remains true, making them essential for tasks that require iteration.

In this article, we will explore Python’s control flow mechanisms by focusing on if, else, and while statements. You will learn how to implement these structures to control the flow of your program, evaluate conditions, and repeat operations efficiently.

Understanding the if Statement

The if statement is the simplest and most commonly used control flow structure in Python. It checks whether a specific condition is true and, if so, executes a block of code. If the condition is false, the code is skipped, and the program continues to the next statement.

Syntax of the if Statement

The basic syntax of an if statement is:

if condition:
    # Code block to execute if the condition is true
  • condition: A boolean expression that is evaluated. If the expression evaluates to True, the code block following the if statement is executed. If it evaluates to False, the code block is skipped.
  • Indentation: In Python, indentation is crucial. The code block that should be executed if the condition is true must be indented (usually four spaces). Python uses indentation to define the scope of code blocks, unlike other languages that rely on braces ({}).

Example of an if Statement

Let’s look at a simple example:

temperature = 30

if temperature > 25:
    print("It's a hot day.")

In this example, the variable temperature is compared to 25. If the temperature is greater than 25, the message “It’s a hot day” will be printed. If the temperature is 25 or below, the code inside the if block will be skipped, and nothing will be printed.

The Role of Boolean Expressions

In an if statement, the condition is usually a boolean expression—an expression that evaluates to either True or False. Python supports a variety of operators for comparing values and creating boolean expressions:

  • Comparison operators:
    • == (equal to)
    • != (not equal to)
    • > (greater than)
    • < (less than)
    • >= (greater than or equal to)
    • <= (less than or equal to)
  • Logical operators:
    • and (both conditions must be true)
    • or (at least one condition must be true)
    • not (negates the condition)

Here’s an example using both comparison and logical operators:

age = 18
has_id = True

if age >= 18 and has_id:
    print("You can enter the club.")

In this example, the if statement evaluates two conditions using the and operator: the person must be at least 18 years old, and they must have an ID. If both conditions are true, the message “You can enter the club” will be printed.

The else Statement

The else statement allows you to define an alternative code block that will be executed when the if condition is false. This is useful when you want to ensure that some code is executed no matter the outcome of the condition.

Syntax of the else Statement

The syntax of an if-else structure is:

if condition:
    # Code block to execute if the condition is true
else:
    # Code block to execute if the condition is false

When the if condition evaluates to False, the code inside the else block will be executed.

Example of an if-else Statement

Let’s consider a scenario where we want to check if a person is eligible to vote:

age = 16

if age >= 18:
    print("You are eligible to vote.")
else:
    print("You are not eligible to vote yet.")

In this example, if the age is 18 or older, the program prints “You are eligible to vote.” Otherwise, it prints “You are not eligible to vote yet.” Since the age is 16, the output will be “You are not eligible to vote yet.”

The elif Statement

The elif (short for “else if”) statement allows you to check multiple conditions in sequence. It comes after an if statement and is used to define an additional condition that will be checked if the first if condition is false.

Syntax of the elif Statement

The structure of an if-elif-else chain is as follows:

if condition1:
    # Code block to execute if condition1 is true
elif condition2:
    # Code block to execute if condition2 is true
else:
    # Code block to execute if both conditions are false

Python evaluates each condition in the order they appear. If a condition evaluates to True, the corresponding code block is executed, and the rest of the chain is skipped. If none of the conditions are true, the else block (if present) is executed.

Example of an if-elif-else Statement

Here’s a practical example:

temperature = 10

if temperature > 30:
    print("It's a hot day.")
elif temperature > 20:
    print("It's a warm day.")
elif temperature > 10:
    print("It's a cool day.")
else:
    print("It's a cold day.")

In this example, the program checks several conditions in sequence:

  • If the temperature is greater than 30, it prints “It’s a hot day.”
  • If the temperature is not greater than 30 but greater than 20, it prints “It’s a warm day.”
  • If the temperature is not greater than 20 but greater than 10, it prints “It’s a cool day.”
  • If none of these conditions are true (i.e., the temperature is 10 or lower), it prints “It’s a cold day.”

Since the temperature is 10, the output will be “It’s a cold day.”

Nesting if-else Statements

You can nest if-else statements inside one another to handle more complex conditions. While this is sometimes necessary, it’s important to avoid over-nesting, as deeply nested conditions can make your code harder to read and maintain.

Example of Nested if-else Statements

Let’s look at an example where we check both the age and whether the person has an ID:

age = 20
has_id = True

if age >= 18:
    if has_id:
        print("You can enter the club.")
    else:
        print("You need to show an ID.")
else:
    print("You are too young to enter.")

In this example, if the person is 18 or older, the program checks whether they have an ID. If they do, they can enter the club. If they don’t have an ID, the program prints a message asking for one. If the person is younger than 18, the program skips the inner condition and prints “You are too young to enter.”

While nesting if-else statements can be useful, it’s often better to break complex conditions into simpler checks to keep the code readable.

The while Loop

A while loop is used to repeat a block of code as long as a specified condition remains true. It is especially useful when the number of iterations is not known beforehand, as the loop continues until the condition becomes false.

Syntax of the while Loop

The basic syntax of a while loop is:

while condition:
    # Code block to repeat as long as the condition is true
  • condition: A boolean expression that is evaluated before each iteration. If the condition evaluates to True, the code inside the loop is executed. If it evaluates to False, the loop is exited, and the program continues with the next statement.

Example of a while Loop

Let’s look at a simple example where we print numbers from 1 to 5 using a while loop:

count = 1

while count <= 5:
    print("Count:", count)
    count += 1

In this example, the variable count starts at 1, and the loop continues as long as count is less than or equal to 5. After each iteration, count is incremented by 1. The loop prints the current value of count during each iteration.

Once count becomes 6, the condition count <= 5 evaluates to False, and the loop stops.

Infinite Loops

A common pitfall with while loops is the creation of infinite loops—loops that never terminate because the condition never becomes false. This often happens when the loop condition depends on a variable that is not correctly updated within the loop.

For example, the following code creates an infinite loop because count is never incremented:

count = 1

while count <= 5:
    print("Count:", count)

To avoid infinite loops, always ensure that the condition can eventually become false by updating the relevant variables within the loop.

Breaking Out of Loops and Skipping Iterations

In the previous section, we introduced the basic structure of while loops in Python and how they are used to repeat a block of code as long as a specified condition is true. Now, let’s dive deeper into more advanced loop control mechanisms, such as breaking out of loops and skipping iterations. These mechanisms allow you to have greater control over how loops behave, which is useful when you need to terminate a loop early or skip certain iterations based on conditions.

The break Statement

The break statement is used to exit a loop prematurely, regardless of whether the loop condition is still true. When Python encounters a break statement inside a loop, it immediately stops the loop and moves on to the next line of code after the loop.

Syntax of the break Statement

The break statement is simple to use and can be placed inside any loop, whether it’s a while loop or a for loop.

while condition:
    # Code to execute
    if some_condition:
        break
    # More code to execute

Example of Using the break Statement

Let’s look at a practical example where we want to exit the loop once a specific condition is met. Suppose we are simulating a basic login system that allows the user to try entering their password a maximum of three times. If they enter the correct password before exhausting their attempts, we can use break to exit the loop early.

correct_password = "password123"
attempts = 0

while attempts < 3:
    user_input = input("Enter your password: ")
    if user_input == correct_password:
        print("Access granted!")
        break  # Exit the loop if the password is correct
    else:
        print("Incorrect password.")
        attempts += 1

if attempts == 3:
    print("Access denied. Too many attempts.")

In this example, the loop allows the user to input their password up to three times. If the user enters the correct password, the break statement is triggered, and the loop ends immediately. If the user fails to enter the correct password after three attempts, the loop ends naturally, and the program prints “Access denied.”

The continue Statement

The continue statement allows you to skip the rest of the current loop iteration and move directly to the next iteration. Unlike break, which terminates the entire loop, continue just skips the remaining code in the current iteration and checks the loop condition again to decide whether to proceed with the next iteration.

Syntax of the continue Statement

The continue statement is often used inside loops where certain conditions need to be skipped without ending the loop entirely.

while condition:
    if some_condition:
        continue  # Skip the rest of the current iteration
    # Code to execute if condition is not met

Example of Using the continue Statement

Suppose we want to print all numbers from 1 to 10 except for the number 5. We can use the continue statement to skip the iteration when the number is 5.

number = 0

while number < 10:
    number += 1
    if number == 5:
        continue  # Skip printing the number 5
    print(number)

In this example, the loop increments number by 1 in each iteration and prints the number. When the number is 5, the continue statement is triggered, causing the loop to skip that iteration. The result is that all numbers from 1 to 10 are printed, except for 5.

1
2
3
4
6
7
8
9
10

Nested Loops and Control Flow

Python allows you to nest loops inside other loops, which can be useful for tasks like iterating over multi-dimensional data structures (e.g., lists of lists) or performing complex operations where each step requires multiple iterations. When working with nested loops, the control flow mechanisms (break, continue, and others) affect only the innermost loop where they are used, unless you explicitly manage the behavior to control outer loops.

Example of Nested Loops

Let’s explore an example where we print a simple multiplication table using nested loops:

rows = 5
columns = 5

for i in range(1, rows + 1):
    for j in range(1, columns + 1):
        product = i * j
        print(f"{product:2}", end=" ")
    print()  # Move to the next line after each row

In this example, the outer loop (for i in range(1, rows + 1)) controls the rows of the table, while the inner loop (for j in range(1, columns + 1)) controls the columns. The print statement inside the inner loop prints the product of i and j. The output will look like this:

 1  2  3  4  5
 2  4  6  8 10
 3  6  9 12 15
 4  8 12 16 20
 5 10 15 20 25

Breaking Out of Nested Loops

If you need to exit both the inner and outer loops simultaneously, Python doesn’t provide a direct mechanism for breaking out of multiple loops with a single break statement. However, there are several ways to work around this limitation, such as using flags or raising exceptions.

Example: Using a Flag to Break Out of Nested Loops

Here’s how you can use a flag to break out of nested loops:

found = False

for i in range(5):
    for j in range(5):
        if i * j == 12:
            found = True
            break  # Exit the inner loop
    if found:
        break  # Exit the outer loop as well

print("Exited both loops")

In this example, the variable found is used as a flag to indicate when we need to exit both loops. When the condition i * j == 12 is met, the inner loop breaks, and the outer loop checks the found flag to decide whether to break as well.

Infinite Loops and How to Avoid Them

An infinite loop occurs when the condition for a while loop never becomes false, causing the loop to run indefinitely. This is often a mistake in code, but there are also legitimate use cases for infinite loops, such as programs that wait for user input or continuously monitor certain conditions.

Example of an Infinite Loop

Here’s a simple example of an infinite loop:

while True:
    user_input = input("Type 'exit' to stop the loop: ")
    if user_input == "exit":
        break

In this example, the while True condition ensures that the loop runs indefinitely. However, the break statement provides a way to exit the loop when the user types “exit.”

How to Avoid Unintended Infinite Loops

To avoid creating infinite loops by mistake, always ensure that the condition controlling the loop will eventually become false. This usually means updating the variable or condition inside the loop so that it approaches the termination condition.

For example, if you have a loop that increments a counter, make sure the counter is properly updated to prevent an infinite loop:

count = 0

while count < 5:
    print(count)
    count += 1  # This ensures the loop condition will eventually be False

Without the count += 1 line, the loop would run indefinitely, since count would always remain 0, causing the condition count < 5 to stay True.

Combining while Loops with else

In Python, you can combine a while loop with an else statement. The else block executes only when the while loop finishes naturally (i.e., when the condition becomes false). If the loop is terminated with a break statement, the else block is skipped.

Syntax of while-else

The structure of a while-else loop is as follows:

while condition:
    # Code to execute in the loop
else:
    # Code to execute if the loop finishes naturally

Example of a while-else Loop

Let’s look at an example where the loop runs until the user guesses the correct number, and if they fail to guess it within three attempts, the else block provides feedback:

secret_number = 7
attempts = 0

while attempts < 3:
    guess = int(input("Guess the number: "))
    if guess == secret_number:
        print("You guessed it!")
        break
    attempts += 1
else:
    print("Sorry, you're out of attempts.")

In this example, the else block is executed if the user doesn’t guess the secret number within three attempts. However, if the user guesses the correct number before running out of attempts, the loop ends with break, and the else block is skipped.

Advanced Use of the while Loop

The while loop is not only useful for simple iteration tasks, but it can also handle more advanced scenarios, such as waiting for events, monitoring conditions in real time, or building interactive applications.

Example: Implementing a Countdown Timer

Let’s create a simple countdown timer using a while loop:

import time

countdown = 5

while countdown > 0:
    print(f"Countdown: {countdown}")
    time.sleep(1)  # Pause for 1 second
    countdown -= 1

print("Time's up!")

In this example, the while loop runs as long as countdown is greater than zero. After each iteration, the program pauses for one second using the time.sleep() function, then decrements countdown by 1. Once the countdown reaches zero, the loop ends, and the program prints “Time’s up!”

Practical Applications of Control Flow and Loops in Real-World Python Programming

Now that you’ve learned about the if, else, and while statements, as well as more advanced control flow techniques such as break, continue, and while-else, it’s time to explore how these concepts apply to real-world programming. Control flow and loops form the backbone of many programming tasks, including data processing, automation, user interaction, and event handling.

In this section, we’ll walk through practical examples that illustrate how to use control flow structures and loops to solve common problems, ensuring that your programs are both efficient and readable.

Data Processing with Loops

One of the most common use cases for loops is processing data. Whether you’re working with lists, files, or large datasets, loops allow you to iterate over collections and apply transformations or calculations to each item.

Example: Calculating the Average of a List

Suppose you have a list of numbers, and you need to calculate the average. You can use a while loop or a for loop to iterate through the list and compute the sum, then divide by the number of elements to get the average.

numbers = [10, 20, 30, 40, 50]
total = 0
count = 0

while count < len(numbers):
    total += numbers[count]
    count += 1

average = total / len(numbers)
print(f"The average is {average}")

In this example, the while loop iterates over the list, summing the values. Once the loop finishes, the program calculates the average by dividing the total by the length of the list. This approach is useful when working with dynamic data, as the list length may vary.

Example: Reading and Processing Data from a File

Another common task in programming is reading data from a file and processing it line by line. This can be easily accomplished using a while loop combined with file operations.

# Open a text file for reading
with open("data.txt", "r") as file:
    line = file.readline()
    
    while line:
        print(line.strip())  # Process the line
        line = file.readline()  # Read the next line

In this example, the while loop continues to read lines from the file until it reaches the end. The strip() function is used to remove any trailing newline characters, and the loop processes each line individually. This is a common technique for handling large text files or logs, where you don’t want to load the entire file into memory at once.

Handling User Input with Control Flow

Interactive programs often rely on user input to drive decisions and actions. Control flow structures such as if-else and while loops are indispensable when handling user input and ensuring that the program responds appropriately to various conditions.

Example: Building a Simple Calculator

Let’s build a simple calculator that takes two numbers and an operator from the user, performs the calculation, and displays the result. The program will also handle invalid inputs using conditional statements.

while True:
    # Get user input
    num1 = float(input("Enter the first number: "))
    operator = input("Enter an operator (+, -, *, /): ")
    num2 = float(input("Enter the second number: "))

    # Perform the calculation based on the operator
    if operator == "+":
        result = num1 + num2
    elif operator == "-":
        result = num1 - num2
    elif operator == "*":
        result = num1 * num2
    elif operator == "/":
        if num2 == 0:
            print("Error: Division by zero is not allowed.")
            continue  # Skip the rest of the loop and ask for input again
        result = num1 / num2
    else:
        print("Invalid operator. Please try again.")
        continue  # Skip the rest of the loop and ask for input again

    print(f"The result is: {result}")

    # Ask if the user wants to perform another calculation
    again = input("Do you want to perform another calculation? (yes/no): ")
    if again.lower() != "yes":
        break

In this example:

  • The program uses a while True loop to continuously ask the user for input.
  • Inside the loop, conditional statements (if-elif-else) are used to perform the correct operation based on the operator entered by the user.
  • The continue statement skips to the next iteration of the loop if the user enters an invalid operator or attempts division by zero.
  • Finally, the program asks the user if they want to perform another calculation, and the loop breaks if the user answers “no.”

Event-Driven Programming with Loops

In event-driven programming, loops are often used to keep a program running while waiting for user input or external events. This is common in applications such as games, GUIs, or server processes that need to remain active until the user or system triggers a specific action.

Example: A Simple Number Guessing Game

Let’s build a basic number guessing game where the player must guess a random number between 1 and 100. The game will provide feedback after each guess and keep track of how many attempts it takes to guess correctly.

import random

secret_number = random.randint(1, 100)
attempts = 0

while True:
    guess = int(input("Guess a number between 1 and 100: "))
    attempts += 1
    
    if guess < secret_number:
        print("Too low!")
    elif guess > secret_number:
        print("Too high!")
    else:
        print(f"Congratulations! You guessed the number in {attempts} attempts.")
        break  # Exit the loop once the correct number is guessed

In this example:

  • The while True loop keeps the game running until the player guesses the correct number.
  • After each guess, the program uses an if-elif-else structure to provide feedback (“Too low!” or “Too high!”) and count the number of attempts.
  • When the player guesses the correct number, the program prints a congratulatory message and exits the loop using break.

This event-driven structure is commonly used in games, simulations, and applications that involve interactive user input.

Best Practices for Using Control Flow and Loops

When writing Python code that relies on control flow and loops, it’s important to follow best practices to ensure that your code is efficient, readable, and maintainable. Here are some key guidelines to keep in mind:

1. Avoid Over-Nesting

Nested loops and conditional statements can make your code difficult to follow and debug. If possible, refactor your code to reduce deep nesting. For example, use break, continue, or helper functions to simplify complex logic.

# Example of reducing nesting with break
for i in range(10):
    for j in range(10):
        if i * j == 25:
            break  # Exit the inner loop once the condition is met

2. Use Descriptive Variable Names

When writing control flow and loops, use clear and descriptive variable names. This helps make the purpose of the loop and conditionals immediately apparent to anyone reading the code.

# Example of using descriptive names
for customer in customers_list:
    if customer.is_active:
        print(f"Sending message to {customer.name}")

In this example, customer and customers_list clearly describe what the loop is iterating over, making the code more readable.

3. Be Cautious with Infinite Loops

Infinite loops can be useful in certain scenarios (e.g., servers or event listeners), but they should be used with care. Always ensure that there is a clear and well-defined exit condition, such as a break statement or user input.

while True:
    user_input = input("Type 'exit' to quit: ")
    if user_input == "exit":
        break  # Exit the infinite loop

4. Optimize Loops for Performance

For large datasets or computationally intensive tasks, it’s important to optimize loops to avoid unnecessary computations. For example, if possible, reduce the number of iterations or move calculations outside of the loop if they don’t need to be repeated.

# Example of optimizing loop performance
constant_value = 5

for i in range(1000):
    result = constant_value * i  # Avoid recalculating constant_value in each iteration

By avoiding redundant calculations inside the loop, you can improve the performance of your code, especially in cases where the loop runs thousands or millions of times.

5. Use else with Loops Carefully

The else statement in loops can be a powerful tool when used correctly, but it’s not always intuitive. Remember that the else block will only execute if the loop completes naturally, without hitting a break statement. This can be useful for certain conditions, but make sure the logic is clear to avoid confusion.

# Example of using else with loops
for number in range(10):
    if number == 7:
        break  # Exit the loop if 7 is found
else:
    print("7 was not found")

In this case, the else block will only run if the number 7 is not found, making the logic of the program clearer to the reader.

Conclusion

Understanding and mastering control flow structures such as if, else, and while loops is essential to writing effective Python programs. These structures allow you to make decisions, repeat actions, and manage complex conditions in your code. Whether you’re processing data, handling user input, building games, or running event-driven applications, control flow is the backbone of program logic.

By applying best practices and optimizing your loops and conditionals, you can write code that is not only functional but also efficient, readable, and maintainable. As you continue to practice, you’ll find that control flow is a powerful tool that enables you to build more dynamic and flexible Python applications.

Discover More

Types of Artificial Intelligence

Discover the types of AI, from Narrow AI to hypothetical Self-Aware AI, and their applications,…

Navigating the Android Interface: Essential Tips for Beginners

Learn essential tips for navigating the Android interface, from home screen customization to managing settings,…

What is Model-Based Learning?

Learn what model-based learning is, explore its applications and discover best practices for building scalable,…

Setting Up Your Python Development Environment: Python Installation and IDEs

Learn how to set up your Python development environment, from installing Python to configuring IDEs…

Introduction to Robotics: A Beginner’s Guide

Learn the basics of robotics, its applications across industries, and how to get started with…

What is Supervised Learning?

Learn what supervised learning is, its types, real-world applications and best practices for implementation. A…

Click For More