Today we’ll be talking about multiway branching, and, to be more precise, we’ll see how to cope with the fact that there is no switch statement in Python.
The switch statement is present in many programming languages like C++, C# or Java, to mention just a few. It’s used to select a block of code based on the value of a variable. This is a more concise way of designing a complex conditional block with multiple if statements.
Table of Contents
Multiple if Statements
In Python, there is no switch statement, so you usually use the more verbose construction with multiple ifs:
worker = input("Whose income do you want to check? ")
if worker == "Anne":
print(36000)
elif worker == "Sue":
print(32000)
elif worker == "Mike":
print(27000)
elif worker == "Emma":
print(41000)
elif worker == "Ben":
print(39000)
The output is:
Whose income do you want to check? Emma
41000
Dictionary
You could alternatively use a dictionary:
worker = input("Whose income do you want to check? ")
print({"Anne": 36000,
"Sue": 32000,
"Mike": 27000,
"Emma": 41000,
"Ben": 39000}[worker])
The output is the same.
Default Values
What about default values? With the if statement we can use an else block where the default value can be put:
worker = input("Whose income do you want to check? ")
if worker == "Anne":
print(36000)
elif worker == "Sue":
print(32000)
elif worker == "Mike":
print(27000)
elif worker == "Emma":
print(41000)
elif worker == "Ben":
print(39000)
else:
print("not found")
Output:
Whose income do you want to check? Jack
not found
As far as dictionaries are concerned, there are at least three ways we can use default values:
1) we can use the in membership operator,
2) we can use the dictionary get method,
3) and finally, we can catch and handle an exception in the try and except blocks.
The membership operator
Let’s have a look at the membership operator first. It’s very straightforward: we just check if a given key is in the dictionary and handle accordingly if it isn’t:
worker = input("Whose income do you want to check? ")
workers = {"Anne": 36000,
"Sue": 32000,
"Mike": 27000,
"Emma": 41000,
"Ben": 39000}
if worker in workers:
print(workers[worker])
else:
print("not found") # default
The get method
Now let’s see how the get method can be used on the dictionary. The method returns the value corresponding to the key passed as its first argument or the default value specified as the second argument if the key is not found:
worker = input("Whose income do you want to check? ")
workers = {"Anne": 36000,
"Sue": 32000,
"Mike": 27000,
"Emma": 41000,
"Ben": 39000}
print(workers.get(worker, "not found"))
A try-except block
If we try to access an element by key using square brackets, we get an error if the key is not found. We can handle the error in a try – except construction:
worker = input("Whose income do you want to check? ")
workers = {"Anne": 36000,
"Sue": 32000,
"Mike": 27000,
"Emma": 41000,
"Ben": 39000}
try:
print(workers[worker])
except KeyError:
print("not found") # default
Multiple Branches with Multiple Functions
These were all very basic examples, where nothing interesting besides assigning values was going on. But there also may be functions in the particular branches that do different things. And we can use both the construction with multiple if statements or a dictionary. Here an example of the former:
operation = input(f"""Which operation should I perform:
1 - sing
2 - jump
3 - sleep?
""")
def start_singing():
print(f"la la la...")
def start_jumping():
print(f"hop, hop, hop...")
def run_default_function():
print("This option is unavailable.")
if operation == "1":
start_singing()
elif operation == "2":
start_jumping()
elif operation == "3":
print(f"Good night")
else:
run_default_function()
Here’s a possible output:
Which operation should I perform:
1 - sing
2 - jump
3 - sleep?
3
Good night
Now let’s rewrite it using a dictionary:
def start_singing():
print(f"la la la...")
def start_jumping():
print(f"hop, hop, hop...")
def run_default_function():
print("This option is unavailable.")
operations = {"1": start_singing,
"2": start_jumping,
"3": lambda: print(f"Good night")}
# We need () at the end to run the function selected by the get() method
operations.get(operation, run_default_function)()
The output is still the same.
Here you can watch the video version: