If you are using Python version 3.10 or above, then use the match case statement in your code that will work precisely like a switch case statement in programming.
Understand it using the below code example:
def num_to_word(num):
match num:
case 1:
return "one"
case 2:
return "two"
case 3:
return "three"
case 4:
return "four"
case default:
return "not_found"
result = num_to_word(3)
print("Result is: ", result)
Output
Result is: three
The python code example defines a function called num_to_word() that takes an input of num. The function then uses a match statement to check the value of num.
If the value of num is equal to 1, 2, 3, or 4, the function will return the string "one", "two", "three", or "four" respectively. If the value of num is anything else, the function will return the string "not_found".
The code then calls the num_to_word() function with input 3 and assigns the return value to the variable result. Finally, the code prints the string "Result is: " followed by the value of the result.
Until Python version 3.10, there is no version of Python that has a Switch case statement like other programming languages. But we can use the if-else statement as its replacement. So if you are using the Python version below 3.10 then you can use if-else to implement switch case-like functionality.
Below is the example to implement switch case like scenario using if-else statement.
def num_to_word(num):
if num == 1:
return "one"
elif num == 2:
return "two"
elif num == 3:
return "three"
elif num == 4:
return "four"
else:
return "nothing"
result = num_to_word(3)
print("Result is: ", result)
Output
Result is: three
0 Comments