Calculator with “try-except” in Python

Berivan Küçükkart
Yetkin Yayın
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:

  1. The calculate function is defined, which takes three arguments: chooseAction (the operator), firstNumber, and secondNumber. It checks if the chooseAction is a valid operator and then performs the corresponding arithmetic operation.
  2. The while True: loop ensures that the program keeps running indefinitely.
  3. Within the loop, the try block is used to handle any exceptions that might occur during user input.
  4. The program prompts the user to input an operator (chooseAction) and checks if it's a valid operator. If not, it prints "Wrong input".
  5. If the operator is valid, the program prompts the user to enter two numbers (firstNumber and secondNumber).
  6. The calculate function is called with the provided operator and numbers, and the result is printed.
  7. 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.

--

--