Skip to main content
 首页 » 编程设计

带有菜单功能的 Python 主函数循环不起作用

2025年05月04日23me-sa

我目前是一名正在上 Python 类(class)的大学生。我们的任务是创建这个带有函数的程序。主函数调用菜单,然后我们在主函数中编写一个循环,以根据菜单函数中的用户响应访问其他函数。

我似乎无法让我的循环工作。当我选择一个菜单选项时,没有任何反应。现在,我只有打印语句来测试函数的调用。我想在编写函数之前确保它能正常工作。

如果有人能举例说明调用函数的循环应该是什么样子,那将对我有很大帮助。

def GetChoice(): 
    #Function to present the user menu and get their choice 
 
    #local variables 
    UserChoice = str() 
 
    #Display menu and get choice 
    print() 
    print("Select one of the options listed below:  ") 
    print("\tP\t==\tPrint Data") 
    print("\tA\t==\tGet Averages") 
    print("\tAZ\t==\tAverage Per Zone") 
    print("\tAL\t==\tAbove Levels by Zone") 
    print("\tBL\t==\tBelow Levels") 
    print("\tQ\t==\tQuit") 
    print() 
    UserChoice = input("Enter choice:  ") 
    print() 
    UserChoice = UserChoice.upper() 
 
    return UserChoice 
 
def PrintData(): 
    print("test, test, test") 
 
def AverageLevels(): 
    print("test, test, test") 
 
def AveragePerZone(): 
    print("test, test, test") 
 
def AboveLevels(): 
    print("test, test, test") 
 
def BelowLevels(): 
    print("test, test, test") 
 
def main(): 
    Choice = str() 
 
    #call GetChoice function 
 
    GetChoice() 
 
    #Loop until user quits 
 
    if Choice == 'P': 
        PrintData() 
    elif Choice == 'A': 
        AverageLevels() 
    elif Choice == 'AZ': 
        AveragePerZone() 
    elif Choice == 'AL': 
        AboveLevels() 
    elif Choice == 'BL': 
        BelowLevels() 
 
 
main() 

请您参考如下方法:

循环应该从以下内容开始:

while True: 
    Choice = GetChoice() 

并且菜单的 if 条件应遵循相同的缩进。

如果要添加退出程序的选项,请添加另一个 elif 语句,如下所示:

elif Choice == "Q": 
    break 

这将退出循环并因此结束程序。

(请原谅很多编辑 - 使用手机)