除了工作之外,我怎样才能尝试?

时间:2016-02-22 19:01:53

标签: python try-catch

我无法理解为什么我的尝试以及除了不能用于​​小数。我试图让某人输入介于1 - 0之间的数字并尝试一下,除非有人输入超过1或低于0的数字然后它将返回该功能并让他们输入一个新数字

Prison = []

def prison():
    try:
        print("prison rate of children, adults and teenagers, the prison rate must be between 0-1")
        print("-------------------------------------------------------------------------------------------")
        Prison.append(int(input("enter the prison rate of children : ")))
        Prison.append(int(input("enter the prison rate of adults : " )))
        Prison.append(int(input("enter the prison rate of teenagers : ")))
    except:
        print("it has to be between 0-1, try again")

输出:

prison rate of children, adults and teenagers, the prison rate must be between 0-1
-------------------------------------------------------------------------------------------
enter the prison rate of children : 0.25
it has to be between 0-1, try again

2 个答案:

答案 0 :(得分:1)

您的代码中没有任何内容实际上引发了不在0和1之间的浮点数的异常。手动引发异常的一种方法是:

def _validate_input(value):
    if not (0 < value < 1):
        raise ValueError("Value range must be between 0-1")
    return value

def prison(): 
    try:
        print("prison rate of children, adults and teenagers, the prison rate must be between 0-1") 
        print("-------------------------------------------------------------------------------------------") 
        Prison.append(_validate_input(int(input("enter the prison rate of children : ")))
        Prison.append(_validate_input(int(input("enter the prison rate of adults : " ))) 
        Prison.append(_validate_input(int(input("enter the prison rate of teenagers : ")))
    except ValueError as e:
        print(e)

答案 1 :(得分:0)

您可以声明自定义例外:

class MyException(Exception):
    pass

try:
    my_input = float(input('enter the prison rate of adults: '))
    if not (0 <= my_input <= 1):
        raise MyException('it has to be between 0-1, try again')
except MyException as e:
    print(e)

如果0.25是可能的值,则应将输入转换为float而不是int