Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/339.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/tfs/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 几个无全局变量的函数_Python_List_Variables_Global - Fatal编程技术网

Python 几个无全局变量的函数

Python 几个无全局变量的函数,python,list,variables,global,Python,List,Variables,Global,我想知道如何在没有全局变量的情况下生成这段代码 我自己也试过了,但它似乎涉及返回,但它不会返回到“菜单”(主菜单列表)。此代码的要点是始终返回菜单,但按“3”(退出程序)时除外 很抱歉,代码太大(太差),我很感激能得到的帮助 import sys word = [] desc = [] def main_list(): print "\nMenu for list \n" print "1: Insert" print "2: Lookup" print "3

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

我自己也试过了,但它似乎涉及返回,但它不会返回到“菜单”(主菜单列表)。此代码的要点是始终返回菜单,但按“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()

看起来您应该在主函数中使用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")
while True:
    # do stuff
    if condition:
        break
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
编辑:正如Prune在下面所说的那样,我没有给出任何理由来解释我的答案,所以这里是:


代码没有返回到您想要的循环的原因是,您正在使用if语句来运行循环。while循环将允许您重复所需的过程,直到需要中断为止。如果您想知道不使用从其他函数调用的main_list()函数的原因,请查看Hosch250的答案。首先,按照前面的“答案”建议清理主循环:删除exit子句,完成后只保留while循环

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

第三,从打印语句中删除对main_列表的调用;当运行完函数的底部时,您将返回到主程序

这能让你动起来吗

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 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")
while True:
    # do stuff
    if condition:
        break
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
为了摆脱全局变量,您需要将变量传递到方法中并从中返回

def insert(word, desc):
    # do stuff
现在,我注意到您在
insert()
look()的末尾调用了
main\u list()
。不要这样做。您不需要每次都使用新实例,您需要返回到当前实例。所以,设置如下内容:

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")
while True:
    # do stuff
    if condition:
        break
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 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()

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

可能对现有代码最简单的方法是对其进行类似的重组,这将使
main_list()
通过在其上添加
循环来驱动整个过程,让它把共享变量作为参数传递给其他函数

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

这是一个代码审查添加;它不解决给定的问题。将它移到一个类中,并将全局变量初始化为类变量,函数可以变成类函数。只要确保A)它没有被破坏代码B)你阅读了主题指南,以确定如果被否决的选民可以留下评论,我可以在适当的情况下改进我的答案,那么如何发布以及发布什么将有所帮助。