【问题标题】:Validate float data type python验证浮点数据类型python
【发布时间】:2018-04-05 12:56:11
【问题描述】:

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

【问题讨论】:

    标签: python validation types calculator


    【解决方案1】:

    假设您在这里使用的是 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()、re-raise-ing 或类似的东西。使用except SpecificException: 几乎总是更好。或者,更频繁,except SpecificException as e:,所以你可以用e做一些事情,比如print在错误消息中。)

    【讨论】:

      【解决方案2】:
      # 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) 
      

      【讨论】:

      • 这是 (a) 一个坏主意,(b) 不正确("3.2" 是一个完全有效的 float,但它不会通过 isdigit()),(c) 对于错误的 Python 版本(OP 几乎可以肯定使用 Python 3.x,因为他使用 print 作为函数,input 作为返回字符串的东西等),并且(d)不是标准的 Python 风格(例如,在 while 条件周围添加额外的括号)。
      【解决方案3】:
      while True:
              try:
                *Your Code*
      except ValueError:
              print("Please enter a number:")
              else:
              break
      

      【讨论】:

      • 您好,欢迎来到 SO。很高兴你从帮助别人开始。但是,您的代码如何回答这个问题?您能否对您的代码进行一些解释,为什么您认为它有助于数字验证?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-09-28
      • 1970-01-01
      • 2010-09-24
      • 1970-01-01
      • 2018-11-06
      • 2012-09-21
      相关资源
      最近更新 更多