首页 > 解决方案 > 已定义函数中未解析的引用

问题描述

我试图调用我在代码中定义的函数,但是,它是说它没有定义?错误是我有“add_to()”的地方,它说它没有定义。我在这里做错了什么?

grocery_list = ['salmon', 'beef', 'eggs', 'milk']

print(grocery_list)
question = input("Would you like to add anything to the list?: ")
if question == "yes" or "y" or "Y":
    add_to()
else:
    print("Enjoy your shopping")


def add_to():
    input("Please enter the item you'd like to add: ")
    grocery_list.append(str(input))


print(grocery_list)

标签: pythonpython-3.x

解决方案


你在函数调用之后做了函数声明。请关注:PEP8以获取更多信息,其次,如果从用户那里获取任何输入,您需要存储在一些变量中以使用任何方式。这是完美添加项目的代码。

grocery_list = ['salmon', 'beef', 'eggs', 'milk']

def add_to():
    s= input("Please enter the item you'd like to add: \n")
    grocery_list.append(str(s))

print(grocery_list)
question = input("Would you like to add anything to the list?: \n")
if question == "yes" or "y" or "Y":
    add_to()
else:
    print("Enjoy your shopping")



print(grocery_list)

输出 :

['salmon', 'beef', 'eggs', 'milk']
Would you like to add anything to the list?:
yes
Please enter the item you'd like to add: 
yourhead
['salmon', 'beef', 'eggs', 'milk', 'yourhead']

推荐阅读