r/learnpython • u/Burger5704 • 7h ago
Need help with a calculator project
new to python, Im making a calculator but when i try to make the code be able to handle a word without crashing it just doesnt work, it just goes and ask for the operator without restarting the loop, tried ai to fix it and explain it to me but didnt do nothing.
num1 = None
num2 = None
result = None
while num1 == None or num2 == None:
try:
num1 = float(input("Enter first number: "))
except ValueError:
print("must enter a valid number")
num1 = None
continue
try:
num2 = float(input("enter second number"))
except ValueError:
print("must enter a valid number")
num2 = None
continue
operator = input("Enter operation (+, -, *, /)")
if operator == "+":
result = (num1 + num2)
elif operator == "-":
result = (num1 - num2)
elif operator == "*":
result = (num1 * num2)
elif operator == "/" and num2 == 0:
result = ("cant divide by zero")
elif operator == "/" and num2 != 0:
result = (num1 / num2)
else:
result = ("Invalid operator")
if result == float or int:
print(result)
num1 = None
num2 = Nonenum1 = None
num2 = None
result = None
while num1 == None or num2 == None:
try:
num1 = float(input("Enter first number: "))
except ValueError:
print("must enter a valid number")
num1 = None
continue
try:
num2 = float(input("enter second number"))
except ValueError:
print("must enter a valid number")
num2 = None
continue
operator = input("Enter operation (+, -, *, /)")
if operator == "+":
result = (num1 + num2)
elif operator == "-":
result = (num1 - num2)
elif operator == "*":
result = (num1 * num2)
elif operator == "/" and num2 == 0:
result = ("cant divide by zero")
elif operator == "/" and num2 != 0:
result = (num1 / num2)
else:
result = ("Invalid operator")
if result == float or int:
print(result)
num1 = None
num2 = None