Skip to content

Python3 Conditional Statements

Python conditional statements determine which code blocks to execute based on the execution result (True or False) of one or more statements.

You can understand the execution process of conditional statements through the diagram below:

Code execution process:

Keyword / Function Description Example
if Conditional statement, executes the code block when the condition is True if x > 0:
elif Multi-condition branch (else if) elif x == 0:
else Executes when all conditions are not satisfied else:
pass Empty statement, used as a placeholder to maintain syntax completeness if x > 0: pass
match Structured pattern matching (Python 3.10+, similar to switch) match x: case 1: ...

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
  • If “condition_1” is True, the “statement_block_1” block will be executed
  • If “condition_1” is False, “condition_2” will be evaluated
  • If “condition_2” is True, the “statement_block_2” block will be executed
  • If “condition_2” is False, the “statement_block_3” block will be executed

Python uses elif instead of else if, so the keywords for if statements are: if – elif – else.

Note:

    1. A colon : must be used after each condition, indicating the statement block to be executed when the condition is met.
    1. Use indentation to define statement blocks. Statements with the same indentation level form a statement block.
    1. There is no switch…case statement in Python, but Python 3.10 added match…case, which has similar functionality, see below.

Gif demonstration:

Here is a simple if example:

#!/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 produces the following output:

1 - if expression condition is true
100
Good bye!

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

The following example demonstrates the age calculation for a dog:

#!/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("Corresponding human age: ", human)
 
### Exit prompt
input("Click enter to exit")

Save the above script in a dog.py file and execute it:

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

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

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
#!/usr/bin/python3
 
# Program demonstrates the == operator
# Using numbers
print(5 == 6)
# Using variables
x = 5
y = 8
print(x == y)

Output of the above example:

False
False

The high_low.py file demonstrates number comparison:

#!/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 guessed: "))
 
    if guess == number:
        print("Congratulations, you guessed correctly!")
    elif guess < number:
        print("The guessed number is too small...")
    elif guess > number:
        print("The guessed number is too large...")

Executing the above script produces the following output:

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

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
# !/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 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 2 and 3")

Save the above program to a test_if.py file and the output after execution is:

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

Python 3.10 added match…case conditional statements, eliminating the need for a series of if-else statements.

The object after match is matched against the content after case in sequence. If a match is successful, the matched expression is executed; otherwise, it is skipped. _ can match anything.

The syntax format 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. When no other case can match, this one matches, ensuring a match is always found.

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"
 
print(http_error(400))
print(http_error(404))
print(http_error(418))
print(http_error(500))

The above is an example of outputting HTTP status codes. The output for multiple status codes is:

Bad request
Not found
I'm a teapot
Something's wrong with the internet

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

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

def check_permission(status):
    match status:
        case 200:
            return "OK - Request successful"
        case 301 | 302:
            return "Redirect - Redirect"
        case 401 | 403 | 404:
            return "Not allowed - No permission or not found"
        case 500 | 502 | 503:
            return "Server Error - Server error"
        case _:
            return "Unknown status - Unknown status code"
 
for code in [200, 301, 403, 500, 418]:
    print(f"Status code {code}: {check_permission(code)}")

For more on match…case, refer to: Python match-case Statement