ValueError验证循环

时间:2019-05-08 13:51:50

标签: python

在上了一堂教我们伪代码的课程之后,我从Python开始。如果用户输入的是小数而不是整数,那么如何进行验证循环以继续执行该功能?在当前状态下,我已经知道用户输入的数字超出可接受范围,但是如果用户输入的是十进制数字,则会崩溃。还有另一个可以识别小数的验证循环吗?

def main():
    again = 'Y'
    while again == 'y' or again == 'Y':
        strength_score = int(input('Please enter a strength score between 1 and 30: '))

        # validation loop
        while strength_score < 1 or strength_score > 30 :
            print ()
            print ('Error, invalid selection!')
            strength_score = int(input('Please enter a whole (non-decmial) number between 1 and 30: '))

        # calculations
        capacity = (strength_score * 15)
        push = (capacity * 2)
        encumbered = (strength_score * 5)
        encumbered_heavily = (strength_score * 10)

        # show results
        print ()
        print ('Your carrying capacity is' , capacity, 'pounds.')
        print ('Your push/drag/lift limit is' , push, 'pounds.')
        print ('You are encumbered when holding' , encumbered, 'pounds.')
        print ('You are heavyily encumbered when holding' , encumbered_heavily, 'pounds.')
        print ()

        # technically, any response other than Y or y would result in an exit. 
        again = input('Would you like to try another number? Y or N: ')
        print ()
    else:
        exit()

main()

2 个答案:

答案 0 :(得分:1)

根据您希望的行为而定:

  1. 如果要接受非整数,只需使用float(input())。如果要接受它们但将它们转换为整数,请使用int(float(input()))截断或使用round(float(input()))舍入到最接近的整数。

  2. 如果要打印错误消息并提示输入新号码,请使用try-catch块:

    try:
        strength_score = int(input('Please enter a strength score between 1 and 30: '))
    except ValueError:
        again = input("Invalid input, try again? Y / N")
        continue # skip the rest of the loop
    

答案 1 :(得分:0)

那是因为您将strength_score作为一个整数,而不是一个浮点数。

尝试更改

strength_score = int(input('Please enter a strength score between 1 and 30: '))

strength_score = float(input('Please enter a strength score between 1 and 30: '))

经过0.10.0001的测试,并且都可以正常工作。