Easy Tutorial
❮ Ref Math Isclose Python Joseph Life Dead Game ❯

Python3 Conditional Control

Python conditional statements determine the execution of a block of code based on the result (True or False) of one or more statements.

You can get a simple understanding of the execution process of conditional statements through the diagram below:

Code Execution Process:


if Statement

The general form of an if statement in Python is as follows:

if condition_1:
    statement_block_1
elif condition_2:
    statement_block_2
else:
    statement_block_3

In Python, elif is used instead of else if, so the keywords for the if statement are: if – elif – else.

Note:

Gif Demonstration:

Example

Here is a simple example of an if statement:

#!/usr/bin/python3

var1 = 100
if var1:
    print("1 - if expression condition is true")
    print(var1)

var2 = 0
if var2:
    print("2 - if expression condition is true")
    print(var2)
print("Good bye!")

Executing the above code will produce the following output:

1 - if expression condition is true
100
Good bye!

From the result, we can see that since the variable var2 is 0, the corresponding if statement block did not execute.

The following example demonstrates the calculation and judgment of a dog's age:

#!/usr/bin/python3

age = int(input("Please enter your dog's age: "))
print("")
if age <= 0:
    print("You're 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 the above script in a file named dog.py and execute it:

$ python3 dog.py
Please enter your dog's age: 1

Equivalent to a 14-year-old human.
Press enter to exit

The following are commonly used operators in if statements:

Operator Description
< Less than
<= Less than or equal to
> Greater than
>= Greater than or equal to
== Equal to, compares whether two values are equal
!= Not equal to

Example

#!/usr/bin/python3

# Program demonstrates the == operator
# Using numbers
print(5 == 6)
# Using variables
x = 5
y = 8
print(x == y)

The output of the above example is:

False
False

The high_low.py file demonstrates numerical comparison operations:

#!/usr/bin/python3

# This example demonstrates a number guessing game
number = 7
guess = -1
print("Number guessing game!")
while guess != number:
    guess = int(input("Please enter the number you guess: "))

    if guess == number:
        print("Congratulations, you guessed correctly!")
    elif guess < number:
        print("The number you guessed is too small...")
    elif guess > number:
        print("The number you guessed is too large...")

Executing the above script will produce the following output:

$ python3 high_low.py
Number guessing game!
Please enter the number you guess: 1
The number you guessed is too small...
Please enter the number you guess: 9
The number you guessed is too large...
Please enter the number you guess: 7
Congratulations, you guessed correctly!

Nested if

In nested if statements, you can place an if...elif...else structure inside another if...elif...else structure.

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 program to a file named test_if.py and run it. The output will be:

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

match...case

Python 3.10 introduced the match...case conditional statement, which eliminates the need for a series of if-else statements.

The object following match is sequentially matched with the contents following case. If a match is successful, the corresponding expression is executed; otherwise, it is skipped. The _ can match anything.

The syntax is as follows:

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

case _: is similar to default: in C and Java, matching this clause when none of the other cases match, ensuring a successful match.

Example

mystatus = 400
print(http_error(400))

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"

This is an example that outputs HTTP status codes. The output will be:

Bad request

A case can also set multiple matching conditions, separated by |, for example:

...
    case 401|403|404:
        return "Not allowed"
❮ Ref Math Isclose Python Joseph Life Dead Game ❯