简体   繁体   中英

Why am I getting an error of list not being defined?

I keep getting an error:

NameError: name 'animal_list' is not defined for line 4

I have gone through my code and can't seem to figure out why. Thanks for any help!

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

You are not passing the animals but animal_list , change to this, should work:

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

As the animal_list is within make_list function scope, and you have no access to this name within main() function scope.

As you're returning animal_list from make_list and assign animals to the result, you should just pass this to display_list directly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM