1. The if Statement

The simplest form of a conditional statement is the if statement. It evaluates a condition, and if that condition is True, it executes the block of code indented under it.

Syntax:

if condition:
    # code to execute

Example:

temperature = 30
if temperature > 25:
    print("It's a hot day!")
2. The else Statement

The else statement follows an if statement and its block of code is executed if the if condition is False.

Syntax:

if condition:
    # code if condition is True
else:
    # code if condition is False

Example:


temperature = 20
if temperature > 25:
    print("It's a hot day!")
else:
    print("It's not a hot day!")
  1. The elif Statement

elif (short for else if) allows you to check multiple expressions for True and execute a block of code as soon as one of the conditions evaluates to True.

Syntax:


if condition1:
    # code if condition1 is True
elif condition2:
    # code if condition2 is True
else:
    # code if neither condition is True

Example:

temperature = 20
if temperature > 25:
    print("It's a hot day!")
elif temperature < 15:
    print("It's a cold day!")
else:
    print("It's a pleasant day!")

Using Logical Operators

Logical operators (and, or, not) can combine conditions within if statements to form more complex conditions.

Example:

age = 20
member = True
if age > 18 and member:
    print("You can access the club.")

Nested Conditional Statements

You can nest if statements inside other if statements to check further conditions.

Example:

age = 60
if age > 18:
    if age > 55:
        print("You're eligible for our senior discount!")
    else:
        print("You're eligible to access the club, but no senior discount.")

Conditional Expressions (Ternary Operators)

Python supports conditional expressions that allow you to assign values based on conditions in a single line.

Example:

age = 20
status = "teenager" if age < 20 else "adult"
print(status)

Practical Example: Grade System

Let’s use conditional statements to determine a student’s grade based on their score.

score = 85

if score >= 90:
    grade = 'A'
elif score >= 80:
    grade = 'B'
elif score >= 70:
    grade = 'C'
elif score >= 60:
    grade = 'D'
else:
    grade = 'F'

print(f"Your grade is: {grade}")

This practical example illustrates how to use nested if, elif, and else statements to make complex decisions based on multiple conditions.

How about a switch statement

Python does not have a traditional switch statement like other programming languages such as C, C++, or Java. However, starting from Python 3.10, Python introduced a similar functionality called the match statement, which serves as a more powerful and flexible version of the switch-case feature found in other languages. This feature is part of what’s called “structural pattern matching.”

Using the Match Statement in Python 3.10+

The match statement provides a way to match on the structure of data in a more sophisticated manner than a sequence of if-elif statements. It allows for complex checks and is inherently more readable and concise for certain scenarios.

Here’s how you can use the match statement, which acts similarly to a switch-case:

def http_status_code(code):
    match code:
        case 200:
            return "Success"
        case 404:
            return "Not Found"
        case 401 | 403:
            return "Not Authorized"
        case _:
            return "Other"

# Example usage
print(http_status_code(200))  # Output: Success
print(http_status_code(404))  # Output: Not Found
print(http_status_code(403))  # Output: Not Authorized
print(http_status_code(500))  # Output: Other

#functions will be discussed in the coming chapters

Key Features of the Match Statement

Multiple Patterns: You can match multiple values in a single case. For instance, case 401 | 403: matches either 401 or 403.

Wildcard Pattern: The underscore _ is used as a wildcard that matches anything, similar to the default case in traditional switch statements.

Alternative Before Python 3.10

Before the introduction of the match statement in Python 3.10, developers often used dictionaries or if-elif-else chains as a workaround for switch-case functionality.

Dictionary as a Switch-Case

Dictionaries can be used to map keys to functions or values, providing a way to handle switch-case scenarios:


def success():
    return "Success"

def not_found():
    return "Not Found"

def not_authorized():
    return "Not Authorized"

def default():
    return "Other"

switch_dict = {
    200: success,
    404: not_found,
    401: not_authorized,
    403: not_authorized,
}

code = 404
result = switch_dict.get(code, default)()
print(result)  # Output: Not Found

This method uses dictionary get() function, where the second argument is a default value that mimics the default case in a switch.