I am trying to create a calculator and use defensive programming to avoid unexpected events and user inputs.
I included a try
/except
block for user input & for zero division.
When I input the division operator to calculate a zero division, my loop is not taking me back to input the number. It's taking me back to input the operator.
I also, struggle to re`loop the calculator for the user to start a new calculation.
Many thanks for the help.
while True:
try:
num1 = float(input("Please enter a number:"))
num2 = float(input("Please enter another number: "))
break
except ValueError:
print("Wrong key entered. Please key in a number")
operator = input("Please enter the operator (+, -, *, /): ")
while True:
if operator == "+":
calculation = num1 + num2
entry = ("{} + {} = {}".format(num1,num2,calculation))
print(entry)
elif operator == "-":
calculation = num1 - num2
entry = ("{} - {} = {}".format(num1,num2,calculation))
print(entry)
elif operator == "*":
calculation = num1 * num2
entry = ("{} * {} = {}".format(num1,num2, calculation))
print(entry)
elif operator == "/":
try:
calculation = num1 / num2
entry = ("{} / {} = {}".format(num1, num2, calculation))
print(entry)
break
except ZeroDivisionError:
print("You cannot divide by zero. Please try again!")
choice = input("Continue - Y / No - N: ")
if choice == "N":
break
else:
print("You have not entered a valid operator, please try again.")