python - ValueError 验证循环
问题描述
在上了一门教我们伪代码的课程后,我开始使用 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()
解决方案
取决于您希望行为是什么:
如果要接受非整数,只需使用
float(input())
. 如果您想接受它们但将它们转换为整数,请使用int(float(input()))
截断或round(float(input()))
舍入到最接近的整数。如果要打印错误消息并提示输入新号码,请使用 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
推荐阅读
- c++ - C++ 中全图的优化(内存)实现
- ubuntu - 如何修复 INET 错误“无法加载库”
- jquery - 如何在 CakePHP 4 中正确使用 AJAX/JQuery/JSON?
- java - Selenium:javascript注入后回调Java方法
- node.js - 从 S3 上传和显示图像
- python - 将精灵添加到不与组中的任何精灵发生冲突的组中
- ocaml - 具有循环函数依赖性的递归匹配函数
- php - 通过 php 获取从第一个链接产生的新链接
- internationalization - 部署 Nextjs 应用程序后,vercel 上的 ERR_TOO_MANY_REDIRECTS
- regex - 正则表达式中的一些单词异常