Title here
Summary here
The code example focuses on switch statements in the target language specified in the logo, which is “Python”.
Here’s a basic switch equivalent in Python using if-elif-else:
import datetime
# Basic switch example
i = 2
print(f"Write {i} as ", end="")
if i == 1:
print("one")
elif i == 2:
print("two")
elif i == 3:
print("three")
# Multiple expressions in a case statement
current_day = datetime.datetime.now().weekday()
if current_day in (5, 6):
print("It's the weekend")
else:
print("It's a weekday")
# Switch with non-constant expressions
current_hour = datetime.datetime.now().hour
if current_hour < 12:
print("It's before noon")
else:
print("It's after noon")
# Type switch equivalent using type() and isinstance()
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")
In Python, we use if-elif-else
statements to mimic switch-case logic:
i = 2
print(f"Write {i} as ", end="")
if i == 1:
print("one")
elif i == 2:
print("two")
elif i == 3:
print("three")
Using tuple membership to handle multiple cases:
current_day = datetime.datetime.now().weekday()
if current_day in (5, 6):
print("It's the weekend")
else:
print("It's a weekday")
Conditions based on the current time:
current_hour = datetime.datetime.now().hour
if current_hour < 12:
print("It's before noon")
else:
print("It's after noon")
Using isinstance
to handle type-specific logic:
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 this Python code, you can save it in a file with a .py
extension and run it using the Python interpreter:
$ 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
This demonstrates how to mimic switch-case logic in Python using if-elif-else constructs while focusing on maintaining idiomatic code.