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

Python main function loop with a menu function is not working?

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

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

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

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()

您需要将 GetChoice() 函数的 return 值分配给名称 Choice:

Choice = GetChoice()

您需要像这样分配 Choice 变量,

Choice =  GetChoice()

此外,请注意,您也可以删除这一行,

UserChoice = str()

在python中,您不需要明确指定变量类型。

最后,另一个小建议是将 Choice.upper() 与代码底部的值进行比较。这样,如果有人输入 'p' 它仍然会调用 PrintData()

循环应从以下内容开始:

while True:
    Choice = GetChoice()

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

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

elif Choice == "Q":
    break

这将退出循环,从而结束程序。

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