Recorded and created by Jeffano John, May 2022
Music "Times from", by Madman_ac, https://lmms.io/lsp/?action=show&file...
A concept that was not available in Python was the use of Switch Case Statements. This can be very useful when there could be multiple case results and the need to pick between a certain. In this video, I will go through how to use the Switch Case statement in Python.
A thing to keep note of this is a new feature that is only available in Python Version 10+. So, if you are using an older version, this will be unsuccessful. Once you have made the upgrade, you can continue with this video.
Firstly, we will go through a simple case of a switch case statement. Let’s ask the user for a value.
code = input ("Enter Error Code: ")
In this line, we are asking the user for an Error code.
Next, we will be creating different cases for different error codes.
match int(code):
case 100:
print("Continue")
case 202:
print("Accepted")
So, in this case, if the user inputs a value of 100 or 202, this would be the result.
case 400 | 401:
print("Bad Request & Unauthorized")
In this case, if the user inputs 400 or 401, it will output the same result.
Now, let’s say they input a number that is not in the cases, then it will print
case _:
print ("Error Code Not Recognized")
This can be used for many situations, this is just a sample.
Next, we can use the switch case to read some information and print out an output. Let’s create a variable message and enter “Error Found”.
message = "Error Found"
I am going to add an if statement to check if it is a digit or not which will make some sense in a minute.
if message.isdigit():
response = {"data": message}
else:
response = {"error": message}
So what I did here is that I assigned the message as an error if it is not a digit and if it is, it is assigned as data.
Next, it will be the switch statement.
match response:
case {"error": msg}:
print ("Error:",msg)
So, the first case checks if the message is assigned as an error or data. Since it is given as an error, it will print “Error” and the message.
The next case will be if the message was assigned a value, a digit.
case {"data": data}:
print("Received Data:",data)
It prints Received Data along with the data that was entered.
Let’s test this code out. If I set the message as “File Corruption”, and run the code, it will say “Error: File Corruption”.
Now if I type in a value such as 25, it will print “Received Data: 25”. These case switches can be used when you are reading a value from the computer and want to print out a specific output.
As you can see, this is how Switch Case Statements can be used in Python. 1. You need to make sure you have Python version 10+. 2. Set a variable to user input or a hard codded statement. Then use the match function to match the variable to a case. I hope this video was helpful and have a wonderful day.