1 python validation types calculator
我正在为我的最终项目用 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.")
Run Code Online (Sandbox Code Playgroud)
假设您在这里使用 Python 3.x,以下每一行:
n1 = float(input ("Enter your first number: "))
Run Code Online (Sandbox Code Playgroud)
...ValueError如果给定一些无法转换为浮点数的东西,则会引发一个。
因此,与其验证然后转换,不如尝试转换,让转换器成为它自己的验证器。
例如,而不是这样:
n1 = float(input ("Enter your first number: "))
n2 = float(input ("Enter your second number: "))
print ("Your result is: ", n1 + n2)
Run Code Online (Sandbox Code Playgroud)
… 你可以这样做:
while True:
try:
n1 = float(input ("Enter your first number: "))
n2 = float(input ("Enter your second number: "))
except ValueError:
print("When I ask for a number, give me a number. Come on!")
else:
print ("Your result is: ", n1 + n2)
break
Run Code Online (Sandbox Code Playgroud)
如果您想分别检查每个值,只需执行两个较小的循环try而不是一个大循环。
与其将这段代码复制粘贴 6 次,不如将其重构为一个函数。像这样的东西:
def get_two_floats():
while True:
try:
n1 = float(input ("Enter your first number: "))
n2 = float(input ("Enter your second number: "))
except ValueError:
print("When I ask for a number, give me a number. Come on!")
else:
return n1, n2
Run Code Online (Sandbox Code Playgroud)
或者,如果您想分别验证每一个:
def get_float():
while True:
try:
return float(input ("Enter your second number: "))
except ValueError:
print("When I ask for a number, give me a number. Come on!")
def get_two_floats();
return get_float(), get_float()
Run Code Online (Sandbox Code Playgroud)
然后你可以这样做:
if choice == "1":
n1, n2 = get_two_floats()
print ("Your result is: ", n1 + n2)
elif choice == "2":
n1, n2 = get_two_floats()
print ("Your result is: ", n1 - n2)
# etc.
Run Code Online (Sandbox Code Playgroud)
附带说明:要捕获除以零,而不是处理所有异常,然后根据输入试图找出导致错误的原因,只需处理ZeroDivisionError. (一般来说,裸机except:是个坏主意,除非你打算使用sys.exc_info()、重新设计raise或类似的东西。使用except SpecificException:几乎总是更好。或者,更频繁地except SpecificException as e:,,所以你可以用 做一些事情e,喜欢print它在错误消息中。)