I'm coding a simple calculator in Python for my final project and I am having trouble validating the user's entered value is a float data type. I want to make it so that if the value is a string type, it would print "Value must be an integer or decimal - Please enter a valid number", and then loop it back to asking for the user input until the user gives a valid entry. I tried, but I am getting stuck. So here is my code so far:
keepProgramRunning = True
print ("Welcome to the Calculator Application!")
good = True
while keepProgramRunning:
print ("1: Addition")
print ("2: Subtraction")
print ("3: Multiplication")
print ("4: Division")
print ("5: Quit Application")
choice = input("Please choose what you would like to do: ")
if choice == "1":
n1 = float(input ("Enter your first number: "))
n2 = float(input ("Enter your second number: "))
print ("Your result is: ", n1 + n2)
elif choice == "2":
n1 = float(input ("Enter your first number: "))
n2 = float(input ("Enter your second number: "))
print ("Your result is: ", n1 - n2)
elif choice == "3":
n1 = float(input ("Enter your first number: "))
n2 = float(input ("Enter your second number: "))
print ("Your result is: ", n1 * n2)
elif choice == "4":
n1 = float(input ("Enter your first number: "))
n2 = float(input ("Enter your second number: "))
try:
print ("Your result is: ", n1 / n2)
except:
if n2 == 0:
print ("Zero Division Error - Enter Valid Number")
while good:
n2 = float(input ("Enter your second number: "))
if n2!=0:
good =False
print ("Your result is: ", n1 / n2)
elif choice == "5":
print ("Thank you for using the calculator. Goodbye!")
keepProgramRunning = False
else:
print ("Please choose a valid option.")