首页 > 解决方案 > 蟒蛇其他:什么都不做

问题描述

如果用户在不存在的菜单中选择选项,我希望我的程序一无所有。

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()' 导致刷新菜单“页面”

标签: pythonif-statement

解决方案


我只会使用一个一直等待有效输入的循环。它请求输入,如果它不是有效选项之一,它将继续等待输入。

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 语句来请求用户提供有效选项。


推荐阅读