几个没有全局变量的函数

Several functions without global variable

我想知道如何在没有全局变量的情况下编写这段代码。

我自己试过了,好像涉及到return,但是又回不去"menu"(main_list)。这段代码的要点是总是 return 到菜单,除非按“3”(退出程序)。

对于大(和坏)的代码,我很抱歉,我很感激我能得到的所有帮助。

import sys
word = []
desc = []

def main_list():

    print "\nMenu for list \n"
    print "1: Insert"
    print "2: Lookup"
    print "3: Exit program"

    choice = raw_input()
    print "Choose alternative: ", choice

    if choice.isdigit():
        choice = int(choice)
        if choice == 1:
            insert()
        elif choice == 2:
            look()
        elif choice == 3:
            sys.exit()
        else:
            print "Error: Not a valid choice \n", main_list()
    else:
        print "Error: Not a valid choice \n", main_list()

def insert():
    ins = raw_input("Word to insert: ")
    if ins not in word:
        word.append (ins)
    else:
        print "Error: Word already exist \n", main_list()       
    desc.append(raw_input ("Description of word: "))
    main_list()

def look():
    up = raw_input("Word to lookup: ")
    if up not in word:
        print "Error: Word not found \n", main_list()
    i = 0
    while up != word[i]:
        i += 1
    if up == word[i]:
        print "Description of word: ", desc[i]
    main_list()

看起来你应该在你的 main 函数中使用 while 循环,这样它只会在你想要的时候退出:

所以像这样:

while choice != 3:
    if choice == 1:
        insert()
    elif choice == 2:
        look()
    elif choice == 3:
        sys.exit()
    else:
        print "Error: Not a valid choice \n"
    print "1: Insert"
    print "2: Lookup"
    print "3: Exit Program"
    choice = int(raw_input("choose alternative")

编辑:正如 P运行e 在下面很好地陈述的那样,我没有为我的回答给出任何理由,所以这里是:

您的代码没有返回到您想要的循环的原因是,您在 运行 循环中使用了 if 语句。 while 循环将允许您重复所需的过程,直到您需要中断。如果您想要一个不使用从其他函数调用的 main_list() 函数的理由,请查看 Hosch250 的答案

首先,按照前面 "answer" 的建议清理主循环:删除 exit 子句并在完成后离开 while 循环。

其次,在参数列表中传递word和desc。将它们添加到函数中的 "def" 行。

第三,从打印语句中删除对 main_list 的调用;当您 运行 离开函数底部时,您将 return 到主程序。

这让你感动吗?

word = []
desc = []
menu = \
    "\nMenu for list \n" \
    "1: Insert\n" \
    "2: Lookup\n" \
    "3: Exit program"

choice = raw_input(menu)
while choice != 3:
    if choice.isdigit():
        choice = int(choice)
        if choice == 1:
            insert(word, desc)
        elif choice == 2:
            look(word, desc)
        else:
           print "Error: Not a valid choice \n", main_list()
    else:
        print "Error: Not a valid choice \n", main_list()

正如 Xeno 所说,您需要一个 while 循环来不断循环输入。对于你的情况,我会建议一个 do-while 循环,但是 Python 没有内置的 do-while,所以你需要模拟一个,可能是这样的:

while True:
    # do stuff
    if condition:
        break

要摆脱全局变量,您需要将变量传递给您的方法并 return 从它们中传递出去。

def insert(word, desc):
    # do stuff

现在,我注意到您在 insert()look() 的末尾调用了 main_list()。不要这样做。不需要每次都新建实例,需要return回到当前实例。所以,设置如下:

def main_list():
    # do stuff

    while True:
        # do more stuff

        if condition:
            break

    # do more stuff

def insert():
    # do stuff - return any new value; otherwise, just let it auto-return

def look():
    # do stuff - return any new value; otherwise, just let it auto-return

将其封装在class中。这样单词列表可以保存在 class 实例中。它不是全局的,您不需要传递它。

class main_list(object):

    def __init__(self):
        self.words = {}

    def run(self):

        while(True):
            print "\nMenu for list \n"
            print "1: Insert"
            print "2: Lookup"
            print "3: Exit program"

            choice = raw_input()
            print "Chose alternative: ", choice

            if choice.isdigit():
                choice = int(choice)
                if choice == 1:
                    self.insert()
                elif choice == 2:
                    self.look()
                elif choice == 3:
                    break
                else:
                    print "Error: Not a valid choice"
            else:
                print "Error: Not a valid choice"

    def insert(self):
        ins = raw_input("Word to insert: ").lower()
        if ins not in self.words:
            desc = raw_input("Enter description of word: ")
            self.words[ins] = desc
        else:
            print "Error: Word already exist"

    def look(self):
        up = raw_input("Word to lookup: ").lower()
        if up in self.words:
            print "description of `%s` is `%s`" % (up, self.words[up])
        else:
            print "Error: Word %s not found" % up

ml = main_list()
ml.run()

请注意,我将代码更改为使用字典。这将避免需要两个单独的列表来保存 worddescription 并提供更快的查找。

可能对现有代码进行最简单的操作就是像这样重构它,这使得 main_list() 通过向其添加 while 循环来驱动整个过程,并拥有它只需将共享变量作为参数传递给其他每个函数。

def main_list():
    word = []
    desc = []

    print "\nMenu for list"
    print "  1: Insert"
    print "  2: Lookup"
    print "  3: Exit program"

    while True:
        choice = raw_input()
        print "Alternative chosen: ", choice

        if choice.isdigit():
            choice = int(choice)
            if choice == 1:
                insert(word, desc)
            elif choice == 2:
                look(word, desc)
            elif choice == 3:
                break
            else:
                print "Error: Not a valid choice"
        else:
            print "Error: Not a valid choice"

def insert(word, desc):
    ins = raw_input("Word to insert: ")
    if ins not in word:
        word.append(ins)
    else:
        print "Error: Word already exist"
    desc.append(raw_input("Description of word: "))

def look(word, desc):
    up = raw_input("Word to lookup: ")
    if up not in word:
        print "Error: Word not found"
    i = 0
    while up != word[i]:
        i += 1
    if up == word[i]:
        print "Description of word: ", desc[i]

main_list()