Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Conditions (if and match)

if, elif, else syntax

if condition:
   # code to execute when condition evals to True
   ...
else:
   # code to execute when condition evals to False
   ...
a = 0
if a == 0:
    print("a is equal to 0.")

    print("another statement in the block")

print("a statement outside the block")
a is equal to 0.
another statement in the block
a statement outside the block

And when the condition is not met:

a = 1
if a == 0:
    print("a is equal to 0.")

    print("another statement in the block")

print("a statement outside the block")
a statement outside the block
a = 1
if a < 0:
    print("a is negative.")
elif a == 0:
    print("a is equal to 0.")
elif a > 0:
    print("a is positive.")
else:
    print("I don't know.")
a is positive.

match keyword

If many elif has to be made, python proposes (since version 3.10) a more lisible and powerful construction using the match keyword:

In this notebook, we cannot use the real input function since there is no user to answer. But in Python, we can locally replace a built-in function by our own function. We just need to define a local function with the same name. We do it in a hidden cell since this is not the subject of this notebook and that defining functions will be seen later.

Notebook Cell
def input(prompt):
    """A silly and positive replacement for the input function

    Don't act like that in real life.
    """
    print(prompt, end="")
    return "y"

Now we can use our local input function that always return "y"

answer = input("hello, say y(es)/n(o)/m(ay be)")
hello, say y(es)/n(o)/m(ay be)

and finally see how we can process the answer:

match answer:
    case "y" | "yes":
        print('process "yes" answer')
    case "n" | "no":
        print('process "no" answer')
    case "m" | "may be":
        print('process the "may be" answer')
    case _:
        print("not a valid answer.")
process "yes" answer

We see that the match statement allows one to express conditions on answer in a concise and elegant way. Actually “Structural Pattern Matching” (the match statement) is extremely powerful. One can read the short documentation for the match statement but there is even a long PEP with a detailed tutorial on this relatively recent feature (introduced in Python 3.10): PEP 636 – Structural Pattern Matching: Tutorial.

The pass keyword, and Ellipsis (a.k.a ...)

The pass instruction is the empty instruction. The typical usage is the following:

if cond:
    # some code
else:
    pass

Your are testing the some code block and know the else block will come but is not yet written. You nevertheless want to have a syntactically correct code. Similarly, you can write

if cond:
    # some code
else:
    ...