1

我正在用 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.")
4

3 回答 3

6

假设您在这里使用 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它在错误消息中。)

于 2013-04-30T00:32:43.743 回答
-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) 
于 2013-04-30T01:03:06.057 回答
-1
while True:
        try:
          *Your Code*
except ValueError:
        print("Please enter a number:")
        else:
        break
于 2018-04-05T03:45:07.757 回答