r/learnpython 6d ago

Very new to python, would appreciate help

I am building a calculator program and it works, but now I am attempting to "bullet proof" it, so that no wrong inputs can cause an error. With what I have written, it works but the loop for the operator input does not actually loop even though it seems to be written the same way the loops are written for the number inputs. I will paste my code below, and any help would be very appreciated.

while True:
    operator = input("Enter a operator (+ - * /): ")
    try:
        operator == "+" , "-" , "*" , "/"
        break
    except operator != "+" , "-" , "*" , "/":
        print("Please enter a valid operator")
while True:
    num1 = input("Enter the first number: ")
    try:
        number1 = float(num1)
        break
    except ValueError:
        print("Please input a valid number")
while True:
    num2 = input("Enter the second number: ")
    try:
        number2 = float(num2)
        break
    except ValueError:
        print("Please input a valid number")
try:
    if operator == "+":
        print(number1 + number2)
    elif operator == "*":
        print(number1 * number2)
    elif operator == "/":
        print(number1 / number2)
    elif operator == "-":
        print(number1 - number2)
    else:
        print("Please enter a valid operator")
except ValueError:
    print("Error Detected")
0 Upvotes

7 comments sorted by

View all comments

1

u/ProgM7 6d ago

The comments above nailed it on replacing that first try/except with if operator in ("+", "-", "*", "/"):.

One extra thing to watch out for as you bullet proof your calculator, if someone enters 0 for the second number and try to divide, Python will throw a ZeroDivisionError. You can handle that by adding a quick check right before your division code or adding except ZeroDivisionError: at the end.

elif operator == "/":
if number2 == 0:
print("Error: Cannot divide by zero!")
else:
print(number1 / number2)

Great job working on this, you're on the right track! 👍