Menu Close

Articles

Python: switch

Switch statement does not exist in Python.  However you can simulate a switch statement using different techniques. We use this program as a training exercise. This lecture is optional, you will not learn anything new here. Just how to use what you have already learned previously.

Switch function:

In the next example we create a fake statement switch using two functions:

Example description

switch: In the example above I use one function “switch” with attribute “value” and one function “case” that return True or False if “switch.value” is one of arguments.

case: Is a function that receive a variable number of arguments. This function uses any(…), a Python function that returns True if any item in an iterable object is True, otherwise it returns False. If the iterable object is empty, the any() function will return False. 

while: Using while loop will iterate one single time ant we can use break statement like a “switch” statement will do. This example demonstrate how using meaningful names for functions python language can be extended in interesting ways.

print: This example also demonstrate how to use print function to print numbers and avoid new line using optional parameter end=”,”.

Testing the program

Open this example live and run it: switch function

Switch class

Next example is similar, except we use a class to hold the value. 

Homework: Run this example live: switch class

These two cases have demonstrate how to use a loop in a smarter way. The trick is to use significant names that “extend” the language. We exploit the fact that “switch” and “case” are not reserved keywords in Python, otherwise this would not work. In other situations you can create “frameworks” specific to your domain, that can be reused in multiple applications, extending the language with”domain specific” functions and classes.

Read next: Closure