我正在用 Python 为我的最终项目编写一个简单的计算器,但我无法验证用户输入的值是浮点数据类型。我想这样做,如果值是字符串类型,它将打印“值必须是整数或小数 - 请输入有效数字”,然后将其循环回询问用户输入,直到用户给出有效的条目。我试过了,但我卡住了。所以这是我到目前为止的代码:
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.")