Python 选择菜单项

0 投票
2 回答
814 浏览
提问于 2025-04-18 04:25

我刚开始学习Python编程,遇到了一些选择选项的问题。我创建了一个菜单,比如有:
说明
餐饮
套餐
添加
当用户选择i、c、a或p时,每个菜单都会显示出来。不过,如果用户先选择了'p'而不是'a',那么我需要设置一个提示,让他们先选择'a'。

INSTRUCTIONS = "I"
CATERING = "C"
PACKAGES = "P" 


    def menu():
        userInput = True 
        while userInput != False:
            print("Instructions
                   Catering
                    Packages")
            userInput = input(">>>")

        if userInput == INSTRUCTIONS:
            instructions()
        elif userInput == CATERING:
            Catering()
        elif userInput == PACKAGES:
            Packages()
        else:
             print("Error")

谢谢

2 个回答

0

如果你在使用python2.x版本,记得用 raw_input() 来代替 input()

def menu():
    mybool == True

    userInput = input("Instructions\nCatering\nPackages\n>>> ")
    b = userInput.lower()[0]
    if b == 'a':
        mybool = True
    elif b == 'i':
        Instructions()
    elif b == 'c':
        Catering()
    elif b == 'p':
        if mybool == True:
            Packages()
        else:
            input('Here is where we display a prompt! ')
    else:
        print("Error")

简单来说,这段代码先把一个变量设为 False,然后等待用户输入。如果用户输入的是 a,那么我们就把 myBool 设为 True。如果用户选择了 p 并且 myBoolTrue(也就是说之前已经选择过 a),程序就会继续执行。否则,它会显示一个提示信息。

0

这里是一个循环中的代码:

def menu():


 while True:
            u_in=raw_input("Input Here:: ")
            u=u_in.lower()
            if u_in=="":
                    continue

            elif u=="i":
                     Instructions()
            elif u=="c":
                    Catering()
            elif u=="p":
                    Packages()

撰写回答