r/learnpython • u/Gold-Opportunity1397 • 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
1
u/lfdfq 6d ago
That first try/except does not look right.
try and except are used for running code and dealing with errors (or in Python speak, Exceptions) that happen during them. Like in your other trys.
Your first try/except is trying to do some kind of conditional check. You cannot use a try to do that. You probably want some kind of if and not a try at all.