python - 验证输入并检查它是否在一个范围内
问题描述
print("What would you like to do:\n1. Enter new information\n2. House-
based statsitics\n3. Specific Criteria statistics")
while True:
try:
option = input("Enter 1 2 or 3: ")
except ValueError:
option = input("Enter 1 2 or 3: ")
if option < 1 and option > 3:
option = input("Enter 1 2 or 3: ")
else:
break
print(option)
我试图确保我的输入在 1 到 3 之间,当我这样做时,我会得到一个 TypeError,但是如果我将它更改为int(option = input("Enter 1 2 or 3: "))
它会在输入字符串时返回错误。
解决方案
或者只是:
option = None
while option not in {'1', '2', '3'}: # or: while option not in set('123')
option = input("Enter 1 2 or 3: ")
option = int(option)
由于对 3 个字符串的限制,在转换为 a 时'1', '2', '3'
甚至不需要捕获 a 。ValueError
int
推荐阅读
- typescript - 在打字稿中扩展原型时如何使用默认参数值?
- google-admin-sdk - AdminDirectory.Members.insert 习惯性地拒绝@hotmail、@outlook 和另一个电子邮件地址,并显示消息:errorException: The email is invalid
- swift - 复制目标文件夹不存在的文件
- java - 从文件中读取以逗号分隔的数字和字符串(java)
- reactjs - 带有 Nextjs 动态导入的 react-odometerjs 不会滚动数字
- php - 使用“array_multisort”对多维数组进行排序不能按预期工作
- ios - 访问 UINavigationController 堆栈上的根控制器的属性
- android - 继续挂起回调函数
- node.js - PurgeCSS 和 Tailwind CSS,如何使用命令行界面保留响应式类?
- c# - 将数据库字段公开给 2 个属性