【问题标题】:Only accept a float between 0 and 1 - python只接受 0 到 1 之间的浮点数 - python
【发布时间】:2016-06-19 04:06:33
【问题描述】:

所以我需要一个非常有效的代码,它可以从用户那里接受 0 到 1 之间的任何数字,并不断提示他们重试,直到他们的输入符合这个标准。 这是我到目前为止所得到的:

def user_input():
    while True:
        global initial_input
        initial_input = input("Please enter a number between 1 and 0")
        if initial_input.isnumeric() and (0 <= float(initial_input) <= 1):
            initial_input = float(initial_input)
            return(initial_input)
        print("Please try again, it must be a number between 0 and 1")

user_input()

这有效,但只有当数字实际上是 1 或 0 时。如果你在这两者之间输入一个小数(例如 0.6),它会崩溃

【问题讨论】:

  • 如果你在这些之间输入一个小数(例如 0.6),它会崩溃....错误信息是什么?
  • 除了“类'float'的未解析的属性引用'是数字'”之外没有错误消息。循环就像我输入一个不在 1 和 0 之间的数字一样运行(不断要求我再试一次)@Xoce
  • 您将输入转换为浮点数两次,一次 before 您尝试对其调用字符串方法。逐行查看您的代码,直到您了解每个代码在做什么。
  • 那你知道怎么解决吗? @jonrsharpe
  • 是的,但我认为你应该自己解决。

标签: python-3.x error-handling floating-point


【解决方案1】:

您应该使用 try/except 仅当输入是 0 到 1 之间的数字时才返回输入,将错误输入捕获为 ValueError:

def user_input():
    while True:
        try:
            # cast to float
            initial_input = float(input("Please enter a number between 1 and 0"))      # check it is in the correct range and is so return 
            if 0 <= initial_input <= 1:
                return (initial_input)
            # else tell user they are not in the correct range
            print("Please try again, it must be a number between 0 and 1")
        except ValueError:
            # got something that could not be cast to a float
            print("Input must be numeric.")

此外,如果您使用自己的代码获得"Unresolved attribute reference 'is numeric' for class 'float'".,那么您使用的是 python2 而不是 python3,因为您仅在 isnumeric 检查之后进行转换,这意味着输入是 eval 的。如果是这种情况,请使用 raw_input 代替 input

【讨论】:

    【解决方案2】:

    您首先需要检查它是否真的是一个浮点数,if "." in initial_input,然后您可以继续进行其他转换:

    def user_input():
        while True:    
            initial_input = input("Please enter a number between 1 and 0").strip()
            if "." in initial_input or initial_input.isnumeric():
                initial_input = float(initial_input)
                if 0 <= initial_input <= 1:
                    print("Thank you.")
                    return initial_input
                else:
                    print("Please try again, it must be a number between 0 and 1")
            else:
                # Input was not an int or a float
                print("Input MUST be a number!")
    
    initial_input = user_input()
    

    【讨论】:

      猜你喜欢
      • 2014-09-22
      • 1970-01-01
      • 2011-07-07
      • 2012-12-17
      • 2016-04-05
      • 2023-04-05
      • 1970-01-01
      相关资源
      最近更新 更多