Skip to content

Conditions

In Python, conditionals are instructions that let you execute code blocks in a selective form, depending if certain conditions are passed. These code blocks can be executed if the condition is true, or omitted if the condition is false.

this instruction evaluates a condition. If that condition is true, the code block that follows the if statement is executed.

This instruction is executed if the condition of an if statement is false.

It lets you evaluate multiple conditions in sequence. If the if statement is false, it evaluates the second condition of elif. If the condition of elif is true, the corresponding code block executes.

Conditions.py
age = 25
if age >= 18:
    print('You are an adult')
else:
    print('You are a minor')
# If the age is less than 18, it will print 'You are a minor'.

As we saw in the Operators section, logical operators are used to combine multiple conditions and get a boolean result, either True or False.

Conditions.py
age = 25
has_identification = True
if age >= 18 and has_identification:
    print('You can enter')
else:
    print('You cannot enter')
# Both conditions must be met. If age is greater than or equal to 18 **and** has identification,
# it prints 'You can enter'.
Conditions.py
is_student = False
is_teacher = True
if is_student or is_teacher:
    print('You have access to campus')
else:
    print('Access denied')
# It's enough for one of the conditions to be true for it to print 'You have access to campus'.
Conditions.py
has_fines = False
if not has_fines:
    print('You can renew your license')
else:
    print('You must pay the fines first')
# 'not' inverts the value. If there are no fines, it prints 'You can renew your license'.

In Python, nested conditionals are if statements inside other if, elif or else statements. This allows evaluating several conditions hierarchically, creating a more complex execution flow based on the combination of conditions.

Conditions.py
is_member = False
age = 15
if is_member:
    if age >= 15:
        print('You have access since you are a member and over 15')
    else:
        print('You have access but are under 15')
else:
    print('You are not a member')
# In this case: not a member therefore no access, despite meeting the condition of being 15 years old.