Switch in D Programming Language

Switch Statements in Python

Switch statements express conditionals across many branches.

Here’s a basic switch, implemented using a dictionary in Python:

def simple_switch(i):
    print(f"Write {i} as", end=" ")
    switcher = {
        1: "one",
        2: "two",
        3: "three",
    }
    print(switcher.get(i, "Invalid number"))

simple_switch(2)

You can use if-elif-else to separate multiple conditions in the same case statement. We use the optional else case in this example as well:

from datetime import datetime

def weekday_switch():
    today = datetime.today().strftime("%A")
    if today in ["Saturday", "Sunday"]:
        print("It's the weekend")
    else:
        print("It's a weekday")

weekday_switch()

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

def time_switch():
    now = datetime.now()
    hour = now.hour
    if hour < 12:
        print("It's before noon")
    else:
        print("It's after noon")

time_switch()

A type switch compares types instead of values. You can use this to discover the type of a variable. In this example, the variable t 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")
$ python switch.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

Next example: Arrays.