我正在使用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.")
答案 0 :(得分:4)
假设您在这里使用Python 3.x,每一行:
n1 = float(input ("Enter your first number: "))
...如果给出了无法转换为浮点数的内容,则会引发ValueError
。
因此,不是验证然后转换,只是尝试转换,让转换器成为自己的验证器。
例如,而不是:
n1 = float(input ("Enter your first number: "))
n2 = float(input ("Enter your second number: "))
print ("Your result is: ", n1 + n2)
......你可以这样做:
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
如果你想分别检查每个值,只需在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
或者,如果您想分别验证每一个:
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()
然后你可以这样做:
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.
作为旁注:要将除法除以零,而不是处理所有异常,然后根据输入找出导致错误的原因,只需处理ZeroDivisionError
。 (一般情况下,除非您要使用except:
,重新sys.exc_info()
,或类似的东西,否则裸raise
是一个坏主意。使用except SpecificException:
是几乎总是更好。或者更常见的是,except SpecificException as e:
,因此您可以使用e
执行某些操作,例如错误消息中的print
。)
答案 1 :(得分:-1)
# get original input
n1 = raw_input("enter your number: ")
while not (n1.isdigit()):
# check of n1 is a digit, if not get valid entry
n1 = raw_input ("enter a valid number: ")
num1 = float(n1) # convert string to float
n2 = raw_input("enter number: ")
while not (n2.isdigit()):
n2 = raw_input("enter a valid number: ")
num2 = float(n2)
答案 2 :(得分:-1)
while True:
try:
*Your Code*
except ValueError:
print("Please enter a number:")
else:
break