Python Tutorial (16) - Conditional Control

Time: Column:Python views:217

Python Conditional Statements

Python's conditional statements are used to decide the flow of code execution based on the result of one or more statements (True or False).

The following diagram gives a basic overview of how conditional statements work:

Python Tutorial (16) - Conditional Control

Code Execution Process

Python Tutorial (16) - Conditional Control

In Python, the general structure of an if statement is as follows:

if condition_1:
    statement_block_1
elif condition_2:
    statement_block_2
else:
    statement_block_3
  • If condition_1 is True, statement_block_1 will be executed.

  • If condition_1 is False, condition_2 will be evaluated.

  • If condition_2 is True, statement_block_2 will be executed.

  • If condition_2 is False, statement_block_3 will be executed.

Python uses elif instead of else if. Thus, the keywords for an if statement are if – elif – else.

Note:

  1. Every condition must be followed by a colon : to indicate that the subsequent block of statements should be executed if the condition is true.

  2. Indentation is used to define the statement block. Statements with the same indentation belong to the same block.

  3. Python does not have a switch...case statement. However, in Python 3.10+, the match...case statement was introduced, which serves a similar function.

Python Tutorial (16) - Conditional Control


Example

The following is a simple if statement example:

#!/usr/bin/python3
 
var1 = 100
if var1:
    print("1 - if statement is True")
    print(var1)
 
var2 = 0
if var2:
    print("2 - if statement is True")
    print(var2)

print("Goodbye!")

Output:

1 - if statement is True
100
Goodbye!


As we can see, since var2 is 0, the if block for var2 was not executed.


Dog Age Calculation Example

This example calculates a dog's age in human years:

#!/usr/bin/python3

age = int(input("Please enter your dog's age: "))
print("")
if age <= 0:
    print("Are you kidding me?")
elif age == 1:
    print("Equivalent to a 14-year-old human.")
elif age == 2:
    print("Equivalent to a 22-year-old human.")
elif age > 2:
    human = 22 + (age - 2) * 5
    print("Equivalent human age: ", human)

# Exit prompt
input("Press enter to exit")

Save this script as dog.py and run it:

$ python3 dog.py
Please enter your dog's age: 1
Equivalent to a 14-year-old human.
Press enter to exit

Common Operators in if Statements

OperatorDescription
<Less than
<=Less than or equal to
>Greater than
>=Greater than or equal to
==Equal to (compares if two values are equal)
!=Not equal to

Example

#!/usr/bin/python3

# Demonstrating the == operator
# Using numbers
print(5 == 6)

# Using variables
x = 5
y = 8
print(x == y)


Output:

False
False



Number Guessing Game Example

This script demonstrates a number guessing game:

#!/usr/bin/python3

# Number guessing game
number = 7
guess = -1
print("Number Guessing Game!")
while guess != number:
    guess = int(input("Please guess the number: "))

    if guess == number:
        print("Congratulations, you guessed it right!")
    elif guess < number:
        print("Your guess is too low...")
    elif guess > number:
        print("Your guess is too high...")

Execution and Output:

$ python3 high_low.py
Number Guessing Game!
Please guess the number: 1
Your guess is too low...
Please guess the number: 9
Your guess is too high...
Please guess the number: 7
Congratulations, you guessed it right!

Nested if Statements

In Python, nested if statements allow you to place an if...elif...else structure inside another if...elif...else structure.

The general structure for nested if statements is as follows:

if expression1:
    statement
    if expression2:
        statement
    elif expression3:
        statement
    else:
        statement
elif expression4:
    statement
else:
    statement

Example

# !/usr/bin/python3
 
num = int(input("Enter a number: "))
if num % 2 == 0:
    if num % 3 == 0:
        print("The number you entered is divisible by both 2 and 3.")
    else:
        print("The number you entered is divisible by 2 but not by 3.")
else:
    if num % 3 == 0:
        print("The number you entered is divisible by 3 but not by 2.")
    else:
        print("The number you entered is not divisible by either 2 or 3.")

Save the above code to a file named test_if.py. After running the script, the output will be:

$ python3 test.py 
Enter a number: 6
The number you entered is divisible by both 2 and 3.

match...case Statement

Introduced in Python 3.10, the match...case statement provides a more readable and efficient alternative to a series of if-else conditions.

The object after match is sequentially compared with the patterns following case. If a match is found, the corresponding code block is executed. The wildcard _ can match anything.

The general syntax for the match...case structure is as follows:

match subject:
    case <pattern_1>:
        <action_1>
    case <pattern_2>:
        <action_2>
    case <pattern_3>:
        <action_3>
    case _:
        <action_wildcard>

The case _: is similar to the default: case in C and Java. When no other case matches, it will always match this one.


Example

def http_error(status):
    match status:
        case 400:
            return "Bad request"
        case 404:
            return "Not found"
        case 418:
            return "I'm a teapot"
        case _:
            return "Something's wrong with the internet"

mystatus = 400
print(http_error(mystatus))

In this example, the script checks HTTP status codes and outputs a corresponding message.

Output:

Bad request



Multiple Match Conditions

A single case can match multiple conditions by using the | operator. For example:

...
    case 401 | 403 | 404:
        return "Not allowed"

This case matches any of the conditions 401, 403, or 404 and executes the corresponding block.