Hello everyone, welcome to nkcoderz.com. In this article we will going to discuss about Python program to find the maximum of two numbers using switch statement.
Table of Contents
Code for python program to find the maximum of two numbers using switch statement
It’s not exactly common to use a switch
statement in Python, since the language has more powerful and flexible control flow constructs like if...elif...else
and conditional expressions
. However, you can use a dictionary to achieve similar functionality to a switch statement, like this:
def maximum(operator, num1, num2):
return {
'>': num1 if num1 > num2 else num2,
'<': num1 if num1 < num2 else num2,
}.get(operator, 'Invalid operator')
print(maximum('>', 1, 2))
print(maximum('<', 4, 2))
print(maximum('!', 2, 5))
Output
2
2
Invalid operator
Explanation
In this program, the maximum()
function takes three arguments: an operator, and two numbers. The function uses a dictionary with the keys being the operator and the values being the conditional expression which compares the numbers and returns the max value. The get()
method is used to get the value associated with the operator key, if it’s not found then it returns the default value which is ‘Invalid operator’.
This is a simple way to use a dictionary to emulate a switch statement. But as I mentioned earlier, if...elif...else
would be a more pythonic way to achieve this goal.
Python program to create a calculator using a switch statement
Conclusion
If you liked this post, then please share this with your friends and make sure to bookmark this website for more awesome content.