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

Posted

技术标签:

【中文标题】带有菜单功能的 Python 主函数循环不起作用?【英文标题】:Python main function loop with a menu function is not working? 【发布时间】:2018-05-04 01:29:04 【问题描述】:

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

我似乎无法让我的循环工作。当我选择一个菜单选项时,什么也没有发生。现在,我只有打印语句来测试函数的调用。我想在编写函数之前确保它有效。

如果有人有一个关于调用函数的循环应该是什么样子的示例,那将对我有很大帮助。

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

【问题讨论】:

【参考方案1】:

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

while True:
    Choice = GetChoice()

并且菜单的 if 条件应该跟在同一个缩进之后。

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

elif Choice == "Q":
    break

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

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

【讨论】:

【参考方案2】:

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

Choice =  GetChoice()

另外,请注意,您也可以像这样删除行,

UserChoice = str()

在 python 中,您不需要显式指定变量类型。

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

【讨论】:

【参考方案3】:

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

Choice = GetChoice()

【讨论】:

以上是关于带有菜单功能的 Python 主函数循环不起作用?的主要内容,如果未能解决你的问题,请参考以下文章

带有数组的函数不起作用

使用 sleep() 函数作为带有 while 循环的计时器不起作用?

带有while循环的Recvall在python中的两个设备之间不起作用

为啥我的主循环在 tkinter 中不起作用?

事件内部功能无法正常工作

主菜单在 iO 上不起作用