带有退出选项的 Python 3 菜单

时间:2021-06-23 14:36:37

标签: python python-3.x loops menu

我正在尝试在 Python 中创建一种 CLI 菜单(对此非常陌生)并且主要是退出选项有问题,它实际上不会退出并跳转到“Oooops that is not right”选项,或重复最后一步。如果你把它作为第一选择,它似乎确实有效

我知道我一定在做一些愚蠢的事情。我曾尝试将变量以及菜单功能本身放在函数的末尾,但这似乎不起作用。

如果有人能指出我正确的方向,请在下面摘录。

def my_menu():
choice = input("Please choose an choice: ")
choice = choice.lower()

while (choice != "quit"):
    if choice == "b":
        a_thing()
        my_menu()
    if choice == "quit":
        break
    else:
        print("Oooops that isn't right")
        my_menu()

def a_thing():
    print("a thing")

my_menu()

2 个答案:

答案 0 :(得分:0)

Try to input the choice another time at the end of the loop, remove the call to the my_menu() function and remove the if choice=="quit" block (because the loop will automatically quit when the choice is set to “退出”)

def my_menu():
    choice = input("Please choose an choice: ").lower()

    while (choice != "quit"):
        if choice == "b":
            a_thing()
        else:
            print("Oooops that isn't right")
        choice = input("Please choose an choice: ").lower()

def a_thing():
    print("a thing")

my_menu()

或者您可以删除循环并仅使用 if 语句进行验证,在“退出”的情况下,您只需使用 return 来中断循环

def my_menu():
    choice = input("Please choose an choice: ").lower()

    if choice == "b":
        a_thing()
    elif choice == "quit":
        return
    else:
        print("Oooops that isn't right")
    my_menu()

def a_thing():
    print("a thing")

my_menu()

答案 1 :(得分:0)

我运行了您的代码,并在第一次迭代时按预期运行。之后,对 my_menu() 的递归调用开始引起问题。

遍历它,首先输入一些随机字符串“hi”,它会进入while循环并使用else大小写。这将调用 my_menu(),然后调用 另一个 while 循环。当您进入新的 while 循环时,您所做的任何退出(例如 break)都不会退出第一个循环,只会退出您当前所在的循环,因此您处于无限循环中,因为您永远无法“ go back”并在第一个循环中更改 choice 的值。

您可以通过对代码进行最少更改来实现此行为的方法如下:

def my_menu():
    choice = ""
    while (choice != "quit"):
        choice = input("Please choose an choice: ")
        choice = choice.lower()
        if choice == "b":
            a_thing()
        if choice == "quit":
            break
        else:
            print("Oooops that isn't right")

def a_thing():
    print("a thing")

my_menu()

(我删除了您对 my_menu() 的递归调用,将输入行移到循环内,并在循环之前初始化了 choice

相关问题