python-3.x 是否有一种方法可以检查输入的类型,如果类型不正确,则循环回输入?

vuktfyat  于 2023-02-01  发布在  Python
关注(0)|答案(2)|浏览(131)
def set_values():
    loopCtrl = 1
    while loopCtrl == 1:
        loopCtrl = 2
        juvenilePopulation = int(input("Enter the population of the juvenile greenfly (1000s) > "))
        if not isinstance(juvenilePopulation, int): loopCtrl = 1
        juvenileSurvivalRate = float(input("Enter the survival rate of juvenile greenfly (decimal) > "))
        if not isinstance(juvenileSurvivalRate, float): loopCtrl = 1
        adultPopulation = int(input("Enter the population of the adult greenfly (1000s) > "))
        if not isinstance(adultPopulation, int): loopCtrl = 1
        adultSurvivalRate = float(input("Enter the survival rate of adult greenfly (decimal) > "))
        if not isinstance(adultSurvivalRate, float): loopCtrl = 1
        senilePopulation = int(input("Enter the population of the senile greenfly (1000s) > "))
        if not isinstance(senilePopulation, int): loopCtrl = 1
        senileSurvivalRate = float(input("Enter the survival rate of senile greenfly (decimal) > "))
        if not isinstance(senileSurvivalRate, float): loopCtrl = 1
        birthRate = float(input("Enter the birthrate of the greenfly > "))
        if not isinstance(birthRate, float): loopCtrl = 1

我有一段公认的丑陋的代码,它目前只是要求一堆输入,将其赋值给变量,然后检查变量的类型,然后循环回到顶部。我真正想要实现的是让代码循环回到输入不正确的输入语句,而不是开始,但在某种程度上比大量的while循环更像Python。

col17t5w

col17t5w1#

将对input的调用替换为如下函数:

def get_value(prompt, validator):
    while True:
        try:
            return validator(input(prompt))
        except ValueError as err:
            print(f"  Invalid value, please try again: {err}")

你可以这样称呼它:

juvenilePopulation = get_value("Enter the population of the juvenile greenfly (1000s) > ", int)
juvenileSurvivalRate = get_value("Enter the survival rate of juvenile greenfly (decimal) > ", float)

运行上面的代码看起来像这样:

Enter the population of the juvenile greenfly (1000s) > foo
  Invalid value, please try again: invalid literal for int() with base 10: 'foo'
Enter the population of the juvenile greenfly (1000s) > 1.1
  Invalid value, please try again: invalid literal for int() with base 10: '1.1'
Enter the population of the juvenile greenfly (1000s) > 12
Enter the survival rate of juvenile greenfly (decimal) > bar
  Invalid value, please try again: could not convert string to float: 'bar'
Enter the survival rate of juvenile greenfly (decimal) > 0.1

注意,在这个例子中,我们使用intfloat这样的基本类型来进行验证,但是你也可以很容易地传入一个自定义函数,例如,如果生存率需要在0和1之间,你可以写:

def validateSurvivalRate(v):
    v = float(v)
    if not 0 < v < 1:
      raise ValueError("surival rate must be between 0 and 1")
    return v

juvenileSurvivalRate = get_value("Enter the survival rate of juvenile greenfly (decimal) > ", validateSurvivalRate)

它看起来像:

Enter the survival rate of juvenile greenfly (decimal) > foo
  Invalid value, please try again: could not convert string to float: 'foo'
Enter the survival rate of juvenile greenfly (decimal) > 1.1
  Invalid value, please try again: surival rate must be between 0 and 1
Enter the survival rate of juvenile greenfly (decimal) > -4
  Invalid value, please try again: surival rate must be between 0 and 1
Enter the survival rate of juvenile greenfly (decimal) > 0.4
cs7cruho

cs7cruho2#

尝试这样做。我不确定这是最佳实践,但您可以重用这些代码。您还可以添加额外的数据类型

def process_values(input_string, input_values, data_type):
    try:
        if not isinstance(eval(input_values), data_type):
            input_values = input(input_string)
            process_values(input_string, input_values, data_type)
    except NameError:
        print('Invalid input')
        input_values = input(input_string)
        process_values(input_string, input_values, data_type)

input_strings = ['Enter the population of the juvenile greenfly (1000s) > ',
                 'Enter the survival rate of juvenile greenfly (decimal) > ',
                 'Enter the population of the adult greenfly (1000s) > ',
                 'Enter the survival rate of adult greenfly (decimal) > ',
                 'Enter the population of the senile greenfly (1000s) > ',
                 'Enter the survival rate of senile greenfly (decimal) >'
                 'Enter the birthrate of the greenfly > '
                 ]

data_types = [int, float, int, float, int, float, float]

for input_string, data_type in zip(input_strings, data_types):
    input_values = input(input_string)
    process_values(input_string, input_values, data_type)

在这里我已经处理了错误。如果你需要更多的异常条件,你可以添加它。

相关问题