【问题标题】:How to use try/except blocks for multiple variables that require user input?如何对需要用户输入的多个变量使用 try/except 块?
【发布时间】:2022-11-12 18:45:25
【问题描述】:
while True:
    try:
        age = int(input("Enter your age: "))
        if age <= 0:
            raise TypeError("Enter a number greater than zero")
    except ValueError:
        print("Invalid age. Must be a number.")
    except TypeError as err:
        print(err)
    except:
        print('Invalid input')
    break 
while True:   
    try:
        height = float(input('Enter your height in inches: '))
        if height <= 0:
            raise TypeError("Enter a number greater than 0")
        break
    except ValueError:
        raise ValueError("Height must be a number.")

我有多个变量需要用户输入才能运行程序。我需要从用户那里获取 3 个变量,他们需要正确输入值。我想我应该为每个变量使用 try/except 块,但是当我为第一个变量使用 try/except 块并开始编写第二个块时,即使用户输入不正确,程序也会跳过异常。

我考虑过使用另一个while循环,但我不确定如何用python编写这个想法;如果满足先前的条件,则移动到下一个代码块。我尝试对两个变量使用相同的 try/except 块但失败了。任何见解都会有所帮助。问题是当输入了一个不正确的值时,程序仍然继续到下一个 try 块。

【问题讨论】:

    标签: python python-3.x try-except


    【解决方案1】:

    您可以将用户输入请求放入为每个唯一变量调用的函数中,请参见以下示例:

    # Function to request input and verify input type is valid
    def getInput(prompt, respType= None):
        while True:
            resp = input(prompt)
            if respType == str or respType == None:
                break
            else:
                try:
                    resp = respType(resp)
                    break
                except ValueError:
                    print('Invalid input, please try again')
        return resp
    

    【讨论】:

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