Python 菜单驱动编程

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25467365/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 20:15:27  来源:igfitidea点击:

Python menu-driven programming

pythonmenupython-3.1

提问by Lbert Hartanto

For menu-driven programming, how is the best way to write the Quit function, so that the Quit terminates the program only in one response.

对于菜单驱动的编程,如何编写 Quit 函数的最佳方式是 Quit 仅在一个响应中终止程序。

Here is my code, please edit if possible:

这是我的代码,如果可能,请编辑:

print("\nMenu\n(V)iew High Scores\n(P)lay Game\n(S)et Game Limits\n(Q)uit")
choose=input(">>> ")
choice=choose.lower()
while choice!="q":
    if choice=="v":
        highScore()
        main()
    elif choice=="s":
        setLimit()
        main()
    elif choice=="p":
        game()
        main()
    else:
        print("Invalid choice, please choose again")
        print("\n")
print("Thank you for playing,",name,end="")
print(".")

When the program first execute and press "q", it quits. But after pressing another function, going back to main and press q, it repeats the main function. Thanks for your help.

当程序第一次执行并按“q”时,它会退出。但是在按下另一个函数后,回到 main 并按 q,它会重复 main 函数。谢谢你的帮助。

回答by khampson

You're only getting input from the user once, before entering the loop. So if the first time they enter q, then it will quit. However, if they don't, it will keep following the case for whatever was entered, since it's not equal to q, and therefore won't break out of the loop.

在进入循环之前,您只能从用户那里获得一次输入。所以如果他们第一次输入q,那么它就会退出。但是,如果他们不这样做,它将继续遵循输入的情况,因为它不等于q,因此不会跳出循环。

You could factor out this code into a function:

您可以将此代码分解为一个函数:

print("\nMenu\n(V)iew High Scores\n(P)lay Game\n(S)et Game Limits\n(Q)uit")
choose=input(">>> ")
choice=choose.lower()

And then call it both before entering the loop and then as the last thing the loop does before looping back around.

然后在进入循环之前调用它,然后作为循环在循环之前做的最后一件事。

Edit in response to comment from OP:

编辑回应来自 OP 的评论:

The following code below, which implements the factoring out I had mentioned, works as I would expect in terms of quitting when qis typed.

下面的代码实现了我提到的分解,在输入q时按我的预期工作。

It's been tweaked a bit from your version to work in Python2.7 (raw_inputvs. input), and also the nameand endreferences were removed from the printso it would compile (I'm assuming those were defined elsewhere in your code). I also defined dummy versions of functions like gameso that it would compile and reflect the calling behavior, which is what is being examined here.

它已从您的版本中进行了一些调整以在Python2.7(raw_inputinput)中工作,并且nameend引用也已从 中删除,print因此它可以编译(我假设这些是在您的代码中的其他地方定义的)。我还定义了类似的函数的虚拟版本,game以便它可以编译并反映调用行为,这就是这里要检查的内容。

def getChoice():
    print("\nMenu\n(V)iew High Scores\n(P)lay Game\n(S)et Game Limits\n(Q)uit")
    choose=raw_input(">>> ")
    choice=choose.lower()

    return choice

def game():
    print "game"

def highScore():
    print "highScore"

def main():
    print "main"

def setLimit():
    print "setLimit"


choice = getChoice()

while choice!="q":
    if choice=="v":
        highScore()
        main()
    elif choice=="s":
        setLimit()
        main()
    elif choice=="p":
        game()
        main()
    else:
        print("Invalid choice, please choose again")
        print("\n")

    choice = getChoice()

print("Thank you for playing,")

回答by johntellsall

Put the menu and parsing in a loop. When the user wants to quit, use breakto break out of the loop.

将菜单和解析放入循环中。当用户想退出时,使用break来跳出循环。

source

来源

name = 'Studboy'
while True:
    print("\nMenu\n(V)iew High Scores\n(P)lay Game\n(S)et Game Limits\n(Q)uit")
    choice = raw_input(">>> ").lower().rstrip()
    if choice=="q":
        break
    elif choice=="v":
        highScore()
    elif choice=="s":
        setLimit()
    elif choice=="p":
        game()
    else:
        print("Invalid choice, please choose again\n")

print("Thank you for playing,",name)
print(".")

回答by Mahesh Kurakula

 def Menu:
     while True:
          print("1. Create Record\n2. View Record\n3. Update Record\n4. Delete Record\n5. Search Record\n6. Exit")
          MenuChoice=int(input("Enter your choice: "))
          Menu=[CreateRecord,ViewRecord,UpdateRecord,DeleteRecord,SearchRecord,Exit]
          Menu[MenuChoice-1]()

回答by Manomoy Biswas

This is a menu driven program for matrix addition and subtraction

这是一个用于矩阵加减的菜单驱动程序

  def getchoice():
        print('\n What do you want to perform:\n 1.Addition\n 2. Subtraction')
        print('Choose between option 1,2 and 3')
        cho = int(input('Enter your choice : '))
        return cho


    m = int(input('Enter the Number of row    : '))
    n = int(input('Enter the number of column : '))
    matrix1 = []
    matrix2 = []

    print('Enter Value for 1st Matrix : ')
    for i in range(m):
        a = []
        for j in range(n):
            a.append(int(input()))
        matrix1.append(a)
    print('Enter Value for 2nd Matrix : ')
    for i in range(m):
        a = []
        for j in range(n):
            a.append(int(input()))
        matrix2.append(a)
    choice = getchoice()
    while choice != 3:
        matrix3 = []
        if choice == 1:
            for i in range(m):
                a = []
                for j in range(n):
                    a.append(matrix1[i][j] + matrix2[i][j])
                matrix3.append(a)
            for r in matrix3:
                print(*r)
        elif choice == 2:
            for i in range(m):
                a = []
                for j in range(n):
                    a.append(matrix1[i][j] - matrix2[i][j])
                matrix3.append(a)
            for r in matrix3:
                print(*r)
        else:
            print('Invalid Coice.Please Choose again.')

        choice = getchoice()