【问题标题】:Why am I getting an error of list not being defined?为什么我收到未定义列表的错误?
【发布时间】:2015-04-20 02:12:36
【问题描述】:

我不断收到错误:

NameError: name 'animal_list' 没有为第 4 行定义

我浏览了我的代码,但似乎无法弄清楚原因。谢谢你的帮助!

import Animal
def main():
    animals = make_list()
    print("Here is the data you entered:", display_list(animal_list))

def make_list():
    animal_list = []

    run = True
    while(run):
        atype = input("What type of animal would you like to create? ")
        aname = input("What is the animals name? ")

        alist = Animal.Animal(atype, aname)

        animal_list.append(alist)

        another = input("Would you like to add more animals (y/n)? ")
        if (another !="y"):
            run = False

    return animal_list

def display_list(animal_list):
    print("Animal List")
    print("------------")
    print()
    for item in animal_list:
        print(item.get_name(), "the", item.get_animal_type(), "is")
main()

【问题讨论】:

    标签: python list python-3.x nameerror


    【解决方案1】:

    你没有通过animals而是animal_list,改成这个,应该可以了:

    def main():
        animals = make_list()
        print("Here is the data you entered:", display_list(animals))
    

    由于animal_listmake_list 函数范围内,您在main() 函数范围内无权访问此名称。

    当您从make_list 返回animal_list 并将animals 分配给结果时,您应该直接将其传递给display_list

    【讨论】:

    • @helpplease,哈哈,不用担心它偶尔会发生在每个人身上。以防万一,我还解释了为什么您无法访问另一个函数中的名称
    猜你喜欢
    • 1970-01-01
    • 2020-09-28
    • 2012-01-30
    • 2013-11-05
    • 1970-01-01
    • 1970-01-01
    • 2014-03-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多