Menu Close


Python: switch simulation

Why 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.


#define a value holder function
# => True
def switch(value):
    return True

#define matching case function
# => True or False
def case(*args):
    return any((arg == switch.value for arg in args))

# Switch example:
print("Describe a number from range:")
for n in range(0,10):
  print(n, end=" ", flush=True)

# Ask for a number and analyze
while switch(n):
    if case(0):
        print ("n is zero;")
    if case(1, 4, 9):
        print ("n is a perfect square;")
    if case(2):
        print ("n is an even number;")
    if case(2, 3, 5, 7):
        print ("n is a prime number;")
    if case(6, 8):
        print ("n is an even number;")
    print ("Only single-digit numbers are allowed.")

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 breack statement like a “swith” statement will do. This example demonstrate how using meaningful names for functions python language can be extended in intresting 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

Describe a number from range:
0 1 2 3 4 5 6 7 8 9
n is a prime number;

Process finished with exit code 0

Read next: Closure