Switch in Python
Here’s how you can translate the given example to Python:
Switch statements express conditionals across many branches. Here’s a basic switch.
i = 2
print(f"Write {i} as ", end='')
if i == 1:
print("one")
elif i == 2:
print("two")
elif i == 3:
print("three")
You can use elif
to separate multiple conditions in the same conditional statement. We use the else
statement in this example as well.
import datetime
weekday = datetime.datetime.now().weekday()
if weekday in [5, 6]: # Saturday is 5 and Sunday is 6
print("It's the weekend")
else:
print("It's a weekday")
Conditional statements without an expression is an alternate way to express if/else logic. Here we also show how the conditions can be non-constants.
t = datetime.datetime.now()
if t.hour < 12:
print("It's before noon")
else:
print("It's after noon")
A type check compares types instead of values. You can use this to discover the type of a variable. In this example, the type
will be checked for 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)}")
what_am_i(True)
what_am_i(1)
what_am_i("hey")
Output:
Write 2 as two
It's a weekday
It's after noon
I'm a bool
I'm an int
Don't know type <class 'str'>
Now that we can translate basic switch statements and conditionals into Python, let’s learn more about the language.