Skip to content
Home » Multiway Branching – the Missing switch Statement

Multiway Branching – the Missing switch Statement

Spread the love

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.

missing switch statement

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.

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.

Your Panda3D Magazine

Make Awesome Games and Other 3D Apps

with Panda3D and Blender using Python.

Cool stuff, easy to follow articles.

Get the magazine here (PDF).

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

Python Jumpstart Course

Learn the basics of Python, including OOP.

with lots of exercises, easy to follow

The course is available on Udemy.

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 

Blender Jumpstart Course

Learn the basics of 3D modeling in Blender.

step-by-step, easy to follow, visually rich

The course is available on Udemy and on Skillshare.

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:


Spread the love

Leave a Reply