Switch Case – Python

In this tutorial I am going to show you how to implement Switch Case using Python. Unlike other languages like C, C++ and Java, Python doesn’t have a Switch Case struct. But as you can see in this tutorial, it is possible to implement a structure identical to the Switch Case using Python.

You don’t need to have installed anything more than your Python interpreter.

Code

As you can see in the code below, there is a class called “Switcher”, this class defines your Switch Case, this is where you insert the code you want to execute in each case, as you can see in example code (#comments).

In this example you need insert the numbers in your python console, if you insert the numbers 1, 2 or 3 in the console, then you can see which case is executed, through the print made by the program. If you insert other number or letter, you see “Invalid Option”, this is the default value. inside the “if method ==” Invalid Option “” you can place any code you want to execute when the chosen option does not exist.

Create a new file “switchCase.py” and copy the code bellow to your file and save it. Then run the code and see the program’s prints on the console.

Your Result:

Please follow and like us:
João Louro

Author: João Louro

Electrical Engineer with special interest in Embedded Systems, Real Time Operating Systems and Audio. With a degree in Electrical and Computer Engineering in the field of Electronics and Computers and currently studying Master's degree in Electrical Engineering.

3 thoughts on “Switch Case – Python

Leave a Reply

Your email address will not be published. Required fields are marked *