Hello everyone, welcome to nkcoderz.com. In this article we will going to discuss about Python program to create a calculator using a switch statement.
Here is an example of a simple calculator program in Python that uses a switch statement to determine which operation to perform:
Table of Contents
Code for python program to create a calculator using a switch statement
def calculator(operator, num1, num2):
if operator == '+':
return num1 + num2
elif operator == '-':
return num1 - num2
elif operator == '*':
return num1 * num2
elif operator == '/':
return num1 / num2
else:
return 'Invalid operator'
print(calculator('+', 1, 2))
print(calculator('-', 4, 2))
print(calculator('*', 2, 5))
print(calculator('/', 8, 4))
print(calculator('%', 8, 4))
Output
3
2
10
2
Invalid operator
Explanation
In this program, the calculator()
function takes three arguments: an operator, and two numbers. The function uses an if...elif...else
statement to check the value of the operator and performs the appropriate arithmetic operation. The function then returns the result of the operation, or an error message if an invalid operator is used.
You can test the program by calling the calculator function with different operators and operands.
Python program to check whether a given alphabet is a vowel or consonant
Conclusion
If you liked this post, then please share this with your friends and make sure to bookmark this website for more awesome content.