Flow Control

Python - A Quick Start for existing Programers

2 min read

Published Sep 16 2025, updated Sep 30 2025


21
0
0
0

Python

If, elif & else statements

If statements are structured using just indents (usually 4 spaces) so define the code flow. if, elif and else blocks cannot be left empty, you can use the pass statement to add content to a block that doesn't run any code, this can be useful in development when the contents of a block aren't known yet, to avoid errors.


An if statement:

a = 10
b = 20
if b > a:
    print("b is greater than a")

An if, elif (else if) statement:

a = 5
if a > 10:
    print("A is greater than 10")
elif a == 5:
    print("A is equal to 5")

An if, else statement:

a = 5
if a >= 10:
    print("A is greater or equal than 10")
else:
    print("A is less than 10")

An if, elif, else statement:

day = 5
if day == 0:
    print("Monday")
elif day == 2:
    print("Tuesday")
elif day == 3:
    print("Wednesday")
elif day == 4:
    print("Thursday")
elif day == 5:
    print("Friday")
else:
    print("Weekend")

Nested if statements (defined by nested indentation):

a = 10
b = 20
if a < b:
    print("a is greater than b")
    if b == 20:
        print("b is 20")
else:
    print("a is not less than b")



Ternary operators

Ternary operators are a way of writing if else code in a short hand way on a single line. They only handle if and else, not elif, however you can stack multiple in a row.


Ternary if statement:

if a > b: print('a is greater than b)

Ternary if else statement:

print('a') if a > b else print('b')

Stacked ternary if else statements:

print("a is less than b") if a < b else print("a is greater less than b") if a > b else print("a is equal to b")



Match statement

This is similar to switch / case statements in other languages.

Case statements are processed from top to bottom. Multiple values can be specified for a case by using the | between them. A catch all of _ can be added to the bottom of the list as this always matches (as it always matches, make sure it is the last case check in the list):

day = 4
match day:
    case 1:
        print("Monday")
    case 2:
        print("Tuesday")
    case 3:
        print("Wednesday")
    case 4:
        print("Thursday")
    case 5:
        print("Friday")
    case 6 | 7:
        print("Weekend")
    case _:
        print("Invalid day")

Another example of multiple value cases:

day = 4
match day:
    case 1 | 2 | 3 | 4 | 5:
        print("weekday")
    case 6 | 7:
        print("Weekend")

Case checks can also have added if conditions combined:

year = 2025
day = 4
match day:
    case 1 | 2 | 3 | 4 | 5 if year == 2025:
        print("Weekday in 2025")
    case 1 | 2 | 3 | 4 | 5 if year == 2024:
        print("Weekday in 2024")
    case _:
        print("No match")
© 2025 SimpleSteps.guide
AboutFAQPoliciesContact