【问题标题】:How can I get the input and see if its in range and get the number again if its not in the range?如何获取输入并查看其是否在范围内,如果不在范围内,则再次获取数字?
【发布时间】:2022-01-08 20:29:14
【问题描述】:
while True:
a = int(input("Enter a number 1: "))
if a in range(121):
    pass
else:
    print("Out of Range")
b = int(input("Enter a number 2: "))
if b in range(121):
    pass
else:
    print("Out of Range")

c =int(input("Enter a number 3: "))
if c in range(121):
    pass
else:
    print("Out of Range")

if a+b+c == 120:
    break
else:
    print("Incorrect Total")

我想检查输入的数字是否在范围内,如果没有再次获得相同的数字,最后检查 3 个变量输入是否加起来为 120,如果不要求再次输入 3 个数字 但是在上面的代码中,当它超出范围时,我无法让它要求相同的数字。

【问题讨论】:

    标签: python python-3.x visual-studio


    【解决方案1】:

    你的想法是对的,但循环有点混乱。这将一直询问,直到您输入“好”值。如果总数不正确,它将按要求重新启动。

    def get_input(n):
        inp = -1
        while inp not in range(121):
            inp = int(input(f"Enter a number {n}: "))  # f-strings require python >= 3.6
        return inp
        
    while True:
        a = get_input(1)
        b = get_input(2)
        c = get_input(3)
        
        if a + b + c == 120:
            break
        else:
            print("Incorrect Total")
    

    【讨论】:

      【解决方案2】:

      你需要循环输入调用

      while True:
          a = int(input("Enter a number 1: "))
          if a in range(121):
              break
          else:
              print("Out of Range")
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-01-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多