python - ValueError 验证循环

标签 python

<分区>

在上了一门教我们伪代码的类(class)后,我开始学习 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()

最佳答案

取决于您希望的行为是什么:

  1. 如果您想接受非整数,只需使用float(input())。如果您想接受它们但将它们变成整数,请使用 int(float(input())) 进行截断或使用 round(float(input())) 进行舍入到最接近的整数。

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

    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
    

关于python - ValueError 验证循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56042386/

相关文章:

python - 使用 apt-get 在 Ubuntu 中安装 SciPy 版本 0.11

python - 从函数和前缀字符串在 Django 中创建默认 ID

python - 在哪里找到python-2.6.0-8.9.28的xml.dom python包,我有一个Linux版本的suse/x86_64版本

python - 使用两个不同的盐对密码进行两次散列并将两个散列保存在同一台服务器上是否安全

python - 仅在 df pandas 中显示特定组

python - 正确的正则表达式是什么?

python - 用于跨蓝图共享资源的 Flask 配置

python - keras - 无法导入名称 Conv2D

python - 为什么在mac上使用PyQt5不能添加图标?

python - 将脚本的输出写入文件时遇到问题