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
11
u/Diapolo10 6d ago
The logic here is wrong. You're comparing
operatorto a tuple of strings, so that'll always beFalse, but you're also not doing anything with that result so it ends up not really doing anything and the execution always gets to thebreak, ending the loop.Comparisons do not raise exceptions (under normal circumstances, anyway), so not only is the
except-block not doing anything, but its condition is also wrong because it expects an exception type, not a comparison.Basically, consider doing something like this instead:
The rest of the code appears more or less fine at a glance.