Menu Close

Articles

Python: switch

Simulation!

Switch statement do not exist in Python.  However we can simulate a switch statement using different techniques. In the next example we create a function switch. This is a fake statement to simulate the switch. We use this program as an example. Read and try to understand the program before reading the description below.

Example:

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.

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

Read next: Closure