【问题标题】:How to limit user input to a list to a specified range of integers? [duplicate]如何将用户对列表的输入限制为指定的整数范围? [复制]
【发布时间】:2019-12-24 05:09:15
【问题描述】:

我想创建一个函数,以交互方式提示用户输入 24 小时 (0 - 23) 的温度。每个温度必须在 -50 到 130 度之间。

如果任何值超出此可接受范围,则应要求用户重新输入该值,直到它在范围内,然后再继续下一个温度。

def getTemps(hourlyTemps):
     hourlyTemps.append(int(input('Enter the temperature of the hour : ')))
            while True:
                try:
                    number1 = hourlyTemps
                    if number1 > -50 or number1 < 130:
                        raise ValueError 
                    break
                except ValueError:
                    print("Invalid integer. The number must be in the range of -50 to 130.")

我不确定我所做的是否可以应用于列表,或者我是否应该尝试不同的方法。任何帮助将不胜感激。

【问题讨论】:

    标签: python validation input while-loop


    【解决方案1】:

    您可以将输入放在 while 循环中并继续询问,直到值正常为止。类似的东西

    while True:
        try:
            temp = int(input("Enter the temperature of the hour: "))
        except ValueError:
            print('Value must be a number.')
        else:
            if -50 <= temp <= 130:
                break
            else:
                print('Value must be between -50 and 130')
    
    # outside the loop
    hourlyTemps.append(temp)
    

    【讨论】:

      【解决方案2】:

      首先,您要将其分解为特定任务。

      1. 从输入中读取一个整数
      2. 检查整数是否在有效范围内
      3. 重复此步骤 24 次

      所以首先读取一个整数并检查范围

      def input_int(msg, min, max):
          # Repeat until a correct value is entered
          while True:
              try:
                  value = int(input(msg))
              except ValueError:
                  print("Input value was not an integer")
              else:
                  # Ensure the range is correct
                  if value < min or value > max:
                      print(f"Value must be between {min} and {max}")
                  else:
                      # Retern the validated value
                      return value
      

      现在重复这个要求 24 次

      hourly_temps = []
      for idx in range(0, 24):
          temp = input_int("Enter the temperature of the hour : ", -50, 130)
          hourly_temps.append(temp)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-03-05
        • 1970-01-01
        • 1970-01-01
        • 2018-12-16
        • 2023-03-04
        • 2019-12-19
        • 1970-01-01
        相关资源
        最近更新 更多