【问题标题】:Input Validation in Python with low and high boundaryPython中的输入验证具有低边界和高边界
【发布时间】:2020-10-13 18:28:07
【问题描述】:

我需要帮助创建一个函数来确保用户的输入是有效的。如果它无效,那么我们需要要求他们重新输入不同的信息。

第一个函数需要有参数prompt,low,high,prompt要求用户输入,low是下界,high是上界。

这是我目前所拥有的:

def get_int(prompt,low,high):
 inputs= int(input(prompt))
while inputs<= low and inputs >=high:
   inputs= int(input(prompt))
return inputs

【问题讨论】:

    标签: python validation input


    【解决方案1】:

    你的条件有一个奇怪的顺序。

    这将确保输入在低边界和高边界之间。如果是,则返回输入,否则再次询问。我添加了一些可选消息来通知用户预期的范围。

    def get_int(prompt, low, high):
        while True:
           inputs = int(input(prompt))
           if low <= inputs <= high:
               return inputs
    #      else:
    #          print(f"Please provide a number between {low} and {high}.")
    

    【讨论】:

      【解决方案2】:

      如果inputs &lt;= low 为真,那么inputs &gt;= high 不能同时为真。因此,通过inputs &lt;= low and inputs &gt;= high 同时检查两者是否为真是没有意义的,而且永远都是假的。如果您使用or 而不是and,您的代码将可以正常工作:

      def get_int(prompt,low,high):
          inputs = int(input(prompt))
          while inputs <= low or inputs >= high:
              inputs = int(input(prompt))
          return inputs
      

      【讨论】:

        【解决方案3】:

        也许使用递归?像这样:

        def user_input():
            value = input("Please enter input: ")
            if not low <= value <= high:
                user_input()
            return value
        

        Recusion 仅在一定深度之前有效,但这可能是数千个输入。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2021-06-21
          相关资源
          最近更新 更多