如果功能错误或参数错误?

时间:2016-03-23 16:25:15

标签: python-3.x

我正在尝试考虑MinValue和MaxValue并打印错误消息,然后继续循环。

应该使用设置参数检查输入,如果输入在参数的任何一侧,那么它应该打印错误消息然后继续循环!但它似乎正在跳过If函数并打印“Number is'x'”。

   def inputInt(prompt, errorMessage = 'Invalid input - Try again.', minValue = 3 , maxValue = None):
while True:
    value = input('Enter a value:')
    try:             
        return int(value)
    except ValueError:
        print(errorMessage)

    if (minValue != 'None' and value < minValue):
            print(errorMessage = 'Value below Minimum')

    if (maxValue != 'None' and value > maxValue):
            print(errorMessage = 'Value above Maximum')

   value = inputInt('Enter an int: ')
   print('Value is', value)

    def inputFloat(prompt, errorMessage = 'Invalid input - Try again.', minValue ='None', maxValue = 'None'):
while True:
    value = input('Enter a value:')
    try:             
        return float(value)
    except ValueError:
        print(errorMessage)

    if (minValue != 'None' and int(value) < minValue):
        print(errorMessage = 'Value below Minimum')


    if (maxValue != 'None' and int(value) < maxValue):
        print(errorMessage = 'Value above Maximum')

    value = inputFloat('Enter an int: ')
    print('Value is', value)

1 个答案:

答案 0 :(得分:0)

return退出该函数并“返回”到它所调用的位置:

def f():
    return 1
    raise RuntimeError("Function continued after return?!?!")
print( f() ) #will not raise the error, prints 1

所以要在转换后做额外的事情,你需要将它作为一个变量存储,然后在最后返回它:

while True:
    value = input(...) #you still probably want to use the prompt variable here
    try:
        value = float(value)
    except ValueError:
        print(errorMessage)
        continue #continue with loop, go back to top of loop

    #other code here

    return value