Switch in Mercury

Based on the provided input, below is the translation of the given code example to Python, as extracted from the input directive.


Switch statements express conditionals across many branches.

Here’s a basic switch.

i = 2
print("Write", i, "as ", end="")

if i == 1:
    print("one")
elif i == 2:
    print("two")
elif i == 3:
    print("three")

You can use multiple conditions in the same elif statement. We use the optional else case in this example as well.

import datetime

current_day = datetime.datetime.today().weekday()

if current_day in [5, 6]:  # Saturday=5, Sunday=6
    print("It's the weekend")
else:
    print("It's a weekday")

A switch without an expression is an alternate way to express if/else logic. Here we also show how the elif expressions can be non-constants.

current_time = datetime.datetime.now()

if current_time.hour < 12:
    print("It's before noon")
else:
    print("It's after noon")

A type switch compares types instead of values. You can use this to discover the type of a variable. In this example, the variable i will have the type corresponding to its clause.

def what_am_i(i):
    if isinstance(i, bool):
        print("I'm a bool")
    elif isinstance(i, int):
        print("I'm an int")
    else:
        print(f"Don't know type {type(i).__name__}")

what_am_i(True)
what_am_i(1)
what_am_i("hey")

To run the program, put the code in a file (e.g., switch_example.py) and use python to execute it.

$ python switch_example.py
Write 2 as two
It's a weekday
It's after noon
I'm a bool
I'm an int
Don't know type str