python - 有没有更好的方法来确保变量只包含数字
问题描述
toss_number = input("How many times do you want to toss the coin?\n")
while True:
if toss_number.isdigit():
break
else:
toss_number = input("Please input NUMBER of times you want to toss a coin.\n")
这些代码行本质上确保了 toss_number 包含一串数字。有没有更好/更有效的方法来做到这一点?
解决方案
另一种方法是使用try
/ except
。如果经常输入一个数字,这将更有效。
while True:
try:
toss_number = int(input("How many times do you want to toss the coin?\n"))
break
except ValueError:
print('You have not entered a NUMBER.')
当ValueError
被引发时,会打印一条消息,但循环没有中断,所以我们返回到while
循环的开头和try
部分。
推荐阅读
- javascript - node.js 是否允许在没有任何等待/预期履行的情况下运行承诺?
- python - 将使用 Firebase 的 python 脚本部署到 Heroku
- amazon-web-services - 如何在特定时间后自动删除 AWS Cognito 用户
- javascript - 如何使用正则表达式验证 ISO8601 日期?
- python - (Python)获得最大递归错误,在这种情况下我应该尝试另一种方法还是覆盖它?
- php - php在表单外提交变量?
- dynamic - 考试包 - 为 Moodle 设置多项练习测验
- c - 为什么不是正在读取的文件的最后一个数值?
- javascript - 文本不显示在图像上 CSS HTML JS
- dart - 为什么 Dart 充当引用传递?