python - 验证输入选择和循环,直到获得 4 个选项之一
问题描述
我在这里尝试了很多变化都无济于事。我有一个包含 4 个选项的菜单,如果在打印出响应并重新提示仅选择 1、> 2、3 或 4 时未选择选项 1、2、3 或 4,我正在尝试循环。我试过了:
print("Options:")
print("Option 1")
print("Option 2")
print("Option 3")
print("Option 4")
choice = int(input("What would you like to choose [1,2,3,4]? "))
while choice not in ['1','2','3','4']:
print: ("Please enter 1, 2, 3 or 4. ")
choice = int(input("What would you like to choose [1,2,3,4]? "))
和
print("Options:")
print("Option 1")
print("Option 2")
print("Option 3")
print("Option 4")
choice = input("What would you like to choose [1,2,3,4]? ")
while choice not '1' and choice not '2' and choice not '3' and choice not '4':
print: ("Please enter 1, 2, 3 or 4. ")
selection = input("What would you like to choose [1,2,3,4]? ")
和
print("Options:")
print("Option 1")
print("Option 2")
print("Option 3")
print("Option 4")
choice = int(input("What would you like to choose [1,2,3,4]? "
while choice != '1' and user_input != '2' and user_input != '3' and choice != 4:
choice = int(input("Please enter 1, 2, 3 or 4. "))
我得到了从语法错误到不正确输出的范围或错误(不会打印“请输入 1、2、3 或 4。”并且不会循环。只有在非常简单的事情之后,不想使用退出语句- 请问我哪里错了?
解决方案
您正在请求一个整数并且您正在寻找它作为char,将您的验证列表更改为整数并且您的第一个选项有效:
print("Options:")
print("Option 1")
print("Option 2")
print("Option 3")
print("Option 4")
choice = int(input("What would you like to choose [1,2,3,4]? "))
while choice not in [1,2,3,4]:
#print: ("Please enter 1, 2, 3 or 4. ")
print("Please enter 1, 2, 3 or 4. ")
choice = int(input("What would you like to choose [1,2,3,4]? "))
推荐阅读
- time - 如何使用 NLTK 获取时间和日期或特定产品名称?
- java - 安卓应用。尝试保存图片时崩溃
- angular - 角材料日期选择器日期格式
- javascript - 在 VUE 中切换样式时边框样式无法正确呈现
- c++ - 如何确定使用的函数的顺序?
- three.js - three.js 从 gltf 异议创建网格
- javascript - Javascript 多函数 setTimeout 同步问题,还是有更好的办法?
- excel - 使用VBA将html源代码提取到excel中
- java - 程序未捕获重复字符串和正确处理的问题
- bash - 在 MacOS Mojave 中找不到 ntpdate 命令