如何在python中创建菜单并使用函数作为我的选项?

时间:2018-04-03 06:14:21

标签: python python-2.7

我希望你做得好!如果你帮助我解决我的这个问题,我将非常感激。我编写了这段代码,根据用户的输入创建字典,然后更新它,按键和值排序,查找项目是否在字典中,计算唯一值的数量,最后将原始字典保存到.txt文件。代码本身工作正常,但我想将它作为一个菜单呈现,以便用户可以选择他/她下一步要做什么,但是当我试图从菜单中调用这些函数时它没有工作,现在我不知道如何正确地做到这一点。你能解释我怎么能这样做吗?提前谢谢!

1 个答案:

答案 0 :(得分:1)

1)添加一个菜单功能,我只做了前三个,这样你就可以得到这个想法(你可以做其余的),例如。

def menu():
    print '1) Create a dictionary'
    print '2) Update the dictionary'
    print '3) Sort the dictionary'
    task = raw_input('Enter the number to perform the corresponding task: ')

    if task == '1':
        user_dict = creating_dictionary()

    elif task == '2':
        try:
            updating_dictionary(user_dict)

        except UnboundLocalError:
            print "A dictionary doesn't exist, you'll have to create one\n"
            creating_dictionary()

    elif task == '3':
        try:
            sorting_dictionary(user_dict)

        except UnboundLocalError:
            print "A dictionary doesn't exist, you'll have to create one\n"
            creating_dictionary()

2)在menu()

中添加main()作为您的第一个语句

3)在每个函数结束时添加对menu()

的调用

4)如果您设置正确,那么main()中您需要的唯一电话就是menu()。您将能够删除所有其他函数调用,因为您将调用的每个函数结束menu()