python - 一旦收到有效输入,如何打破用户选择的循环?
问题描述
如果用户没有选择 1 或 2,我希望代码说“请输入 1 或 2 继续”,该部分有效。但是,如果用户输入“6”,它会要求“请输入 1 或 2 继续”,但如果在无效输入之后直接输入有效输入,则代码无法正确显示。
我试图在没有要求功能的情况下做到这一点,但似乎没有什么能按我的意愿工作。
def requirement():
choice = ""
while choice != "1" and choice != "2":
choice = input ("Please enter 1 or 2 to continue.\n")
if choice == "1" and choice == "2":
return choice
def intro():
print ("Enter 1 to enter the cave\n")
print ("Enter 2 to explore the river\n")
play_again = input ("What would you like to do?\n")
if play_again in "1":
print ("You win!")
elif play_again in "2":
print ("YOU LOSE")
print ("Thanks for playing!")
exit()
else:
requirement()
intro()
解决方案
def intro():
print ("Enter 1 to enter the cave\n")
print ("Enter 2 to explore the river\n")
play_again = input ("What would you like to do?\n")
return play_again
def game(choice):
if choice == "1":
print ("You win!")
elif choice == "2":
print ("YOU LOSE")
print ("Thanks for playing!")
exit()
else:
choice = input ("Please enter 1 or 2 to continue.\n")
game(choice)
game(intro())
该else
语句已经处理了是否输入 1 或 2,因此不需要该requirement
函数。
推荐阅读
- javascript - 错误类型错误:无法读取未定义的属性“pageIndex”
- javascript - JavaScript 调用堆栈中的变量如何在函数返回后仍可访问
- python - 如果我将对象的名称作为字符串并且在 python 中具有属性,如何访问对象的属性?
- pandas - 使用 pd.Series.str.contains 查找列中是否存在字符串
- date - 从纪元时间转换为 (dd/mm/yyyy) 日期格式
- java - 为什么JVM突然缩小eden空间,扩大old空间?(导致性能问题)
- c++ - 是什么导致 Visual Studio 在某些机器上隐藏文件而不在其他机器上隐藏文件?
- sdk - 如何区分类型为 [ 成员 | 的提及 标签 | 渠道 ]?
- typescript - 使用 React Native 测试 React Navigation 的类型安全
- excel - 有没有办法在 Excel 中的单元格上放置下拉菜单以选择要在公式中使用的值?