Calculator with “try-except” in Python
Published in
2 min readAug 14, 2023
In this article, we will code a calculator using the Python programming language and the try-except function. I will use Jupyter Notebook as my IDE. Let’s get started.
Here’s how the code works:
- The
calculate
function is defined, which takes three arguments:chooseAction
(the operator),firstNumber
, andsecondNumber
. It checks if thechooseAction
is a valid operator and then performs the corresponding arithmetic operation. - The
while True:
loop ensures that the program keeps running indefinitely. - Within the loop, the
try
block is used to handle any exceptions that might occur during user input. - The program prompts the user to input an operator (
chooseAction
) and checks if it's a valid operator. If not, it prints "Wrong input". - If the operator is valid, the program prompts the user to enter two numbers (
firstNumber
andsecondNumber
). - The
calculate
function is called with the provided operator and numbers, and the result is printed. - If any exceptions occur during input (such as entering non-numeric values), the
except
block prints "Please enter the correct numbers".
def calculate(chooseAction,firstNumber,secondNumber):
if calculate not in "+-*/":
print("Wrong input")
if calculate == "+":
return (firstNumber + secondNumber)
elif calculate == "-":
return(firstNumber - secondNumber)
elif calculate == "*":
return(firstNumber * secondNumber)
elif calculate == "/":
return(firstNumber / secondNumber)
while True:
try:
chooseAction = input("Choose: +,-,*,/: " )
if chooseAction not in "+-*/":
print("wrong input")
else:
firstNumber = int(input("enter the first number: "))
secondNumber = int(input("enter the second number: "))
print(calculate(chooseAction,firstNumber,secondNumber))
except:
print("Please enter the correct numbers")
Overall, this code is a basic calculator program that allows the user to perform addition, subtraction, multiplication, and division operations using the specified operator and numbers.