python - 蟒蛇其他:什么都不做
问题描述
如果用户在不存在的菜单中选择选项,我希望我的程序一无所有。
def mainMenu():
os.system("clear")
print("menu")
print("1 - option 1")
print("2 - option 2")
selection=str(raw_input(""))
if selection=='1':
some super-interesting things
if selection=='2':
Kim Kardashian with Eskimo riding a polar bear
else:
literally DO NOTHING, no changes, no exiting the program, just takes the input and waits for another command
mainMenu()
如何做到这一点?'pass' 或 'return' 导致退出程序。'mainMenu()' 导致刷新菜单“页面”
解决方案
我只会使用一个一直等待有效输入的循环。它请求输入,如果它不是有效选项之一,它将继续等待输入。
def mainMenu():
os.system("clear")
print("menu")
print("1 - option 1")
print("2 - option 2")
valid_options = ['1', '2']
while True:
selection = str(raw_input(""))
if selection in valid_options:
break
if selection == '1':
some super-interesting things
elif selection == '2':
Kim Kardashian with Eskimo riding a polar bear
mainMenu()
您甚至可以在循环内的 if 中添加 else 语句来请求用户提供有效选项。
推荐阅读
- java - kafka 启用默认轮询分区器
- mysql - 调用模型 [App\Salarie] 上的未定义关系 [pointage]?
- c# - C# 使用 Random 类实例的 Next 方法生成随机数的内部算法是什么?
- django - 路由路径中的“0”导致 NoReverseMatch 错误
- asp.net-core - 部署到 Azure 的 Asp.Net Core WebAPI 不是发出手动设置的 Cookie,而是在本地工作?
- javascript - 在鼠标悬停时打开 div 的不透明度
- javascript - Feathers authenticate('jwt') 用户通过身份验证后,但 req.user 是一个空对象
- python - AttributeError:“QScatterSeries”对象没有属性“点”
- java - Swing:窗口最小化后图形消失
- android - 在使用 kotlin 的非活动类中使用 Toast.makeToast 时出错