Accueil Blog Projets CV Contact

Cet article n'est pas encore disponible en français. Vous lisez la version anglaise.

Python Conditional Statements: If-Else, Expressions, and Match-Case

Sidali Assoul Sidali Assoul 6 min de lecture

Dernière mise à jour le

Introduction

Most of programs don’t execute all of their instructions! thanks to conditional branching statements, programs can make decisions about which code to execute based on the user input, the current state of the program, or the data they’ve already processed.

In this article, you’ll learn how Python makes those decisions using if, elif, else, conditional expressions, and the match statement.

If Statement

Conditionals such as if statements allow us to select which block of code to execute based on a bunch of conditions.

Let’s say that we want to print the priority of a task based on a positive integer value rank

The code below prints “High” when rank is equal to 0, and when it’s not the program skips the block within the if statement condition, so nothing gets printed.

rank = 0 # Change to any other value, to skip the code block within the `if` statement
if rank == 0:
    print("High") # <-- This block gets selected

We can add a contrary case, or a case when the rank is different than 0 using the else keyword.

rank = 0 # Change to anything else, to make the program select the second branch (else side).

if rank == 0:
    print("High")# <-- only this block gets selected
else:
    print("Low")

The rank == 0 condition gets evaluated first, if it’s equal to True the block within the if statement executes and the block within the else keyword gets ignored.

Python if else Explaned

If we wanted to evaluate other cases such as when the rank is equal to 1, we can use elif which is a shorthand for else if, followed by a condition.

For example, here we check wether the rank is equal to 1, before moving to the else case the program evaluate all the elif cases first.

rank = 0 # Change to 0 or 1, or anything else to execute other branches.

if rank == 0:
    print("High")# <-- only this block gets selected
elif rank == 1: # <-- "elif <condition>" stands for "else if <condition>"
    print("Medium")
else:
    print("Low")

Only one branch gets executed in a single program run, other branches are skipped.

Python if else elif conditions

You can add as many elif branches as necessary.


rank = 0 # Change to 0,1,2 or 3, or anything else to execute other branches.

if rank == 0:
    print("High")# <-- only this block gets selected

elif rank == 1:
    print("Medium")
elif rank == 2:
    print("Medium good")

elif rank == 3:
    print("Medium less good")
else:
    print("Low")

Conditional Expression

Another way for writing conditions in Python is by using the ternary expression.

A conditional expression is a one-liner way to write an if-else statement that evaluate to a specific value.

result = true_value if condition else false_value

The above expression reads as follow:

If the condition is true, return the true_value, else return the false_value

For example, Let’s convert our previous if-else statement to a one-liner conditional expression.

rank = 0
if rank == 0:
    print("High")# <-- only this block gets selected
else:
    print("Low")

The above code is equivalent to:

rank = 0 
label = "High" if rank == 0 else "Low"
print(label)

The conditional expression reads as: If rank is equal to zero return “High”, else return “Low”.

Unlike a noraml if statement the else side is required in a conditional expression

Match Case Statement

rank = 0
match rank:
    case 0:
        print("High")
    case 1:
        print("Medium")
    case _:
        print("Low")

The _ wild card is equivalent to an else in an if statement.

The match statement is more powerful than an ordinary if-else statement or a switch-case one that you may have encounter in other languages.

It can be used to match complex structures and patterns.

For example, let’s say that we have a point in space defined with its x, y coordinates.

point = [4, 3] # This creates a list of two elements in Python. 
# The first element is the x coordinate of the point and the second one is the y coordinate

Python Point in Space Match Case Example

Using a match statement we can match complex patterns such as:

  1. Any random point [x,y] defined with its coordinates x,y.
  2. The Origin Point: [0, 0] (The intercection of the x-axis and the y-axis).
  3. Any point on the X-axis [x, 0] (y == 0).
  4. Any point on the Y-axis [0,y] (x == 0)
  5. Any point on the diagonal line [x, y] where (x == y).
point = [4, 4]  

match point:
    case [0, 0]: # <--- (1)
        print("Origin")
        
    case [x, 0]: # <-----(3)
        print(f"Point at the X-axis, at coordinate x = {x}")
        
    case [0, y]: # <----- (4)
        print(f"Point at the Y-axis, at coordinate y = {y}")

    case [x, y] if x == y: # <---- (5)
        print(f"Point is on the diagonal line because x ({x}) equals y ({y})")
        
        
    case [x, y]: # <----- (2)
        print(f"General point in space at coordinates ({x}, {y})")

Summary

if, elif, else

if condition:
    ...
elif another_condition:
    ...
else:
    ...
  • Evaluate conditions from top to bottom.
  • The first condition that evaluates to True is executed.
  • Only one branch executes during a program run.
  • You can have as many elif branches as needed.

Conditional Expression (Ternary)

value = true_value if condition else false_value
  • A one-line if-else that returns a value.
  • The else branch is required.

match Statement

match value:
    case pattern:
        ...
    case _:
        ...

match compares a value against a series of patterns until one matches.

It supports:

  • Exact value matching (case 0)
  • Pattern matching (case [x, y])
  • Variable capture (case [x, 0])
  • Guards (case [x, y] if x == y)
  • A default case (case _)

When to Use Each

  • Use if when evaluating arbitrary boolean conditions.
  • Use a conditional expression when choosing between two values.
  • Use match when matching many fixed cases or structured data.

Key Notes for Memorization

  • Conditions are evaluated top to bottom.
  • Once a branch is selected, every remaining branch is skipped.
  • Conditional expressions always produce a value.
  • match is more powerful than a traditional switch statement because it supports structural pattern matching.
  • The _ wildcard behaves like a default or else branch.

Conclusion

You now know how to make your Python program smart enough to decide on its own which parts of code need to be executed based on its state, using either if, conditional expressions, or match for complex pattern mateching.

But selecting or taking is not enough to write a turing complete programs, you need some constructs that makes it possible to avoid repeating ourselves.

In the next article, we will learn about another type of control flow statement in addition to selection(conditionals), we will unveil the concept of loops, a type of contructs that makes it possible to repeat executing a specific block of code many times or based on a specific conditions.

Continue to Python Loops Masterclass: For-Range, While True, Break, and Continue

Cet article vous a plu ?

Je suis ouvert à de nouveaux postes, en télétravail ou à l'international. Si quelque chose vous a parlé ou si vous souhaitez collaborer, j'adorerais en discuter.

Se connecter sur LinkedIn
Sidali Assoul

Écrit par

Sidali Assoul

Ingénieur logiciel avec 5 ans d'expérience en développement web et mobile full stack, un bilan éprouvé en data science, recherche et solutions IA modernes, avec une approche orientée business pour livrer des produits à forte valeur ajoutée.