定义函数中未解析的引用

时间:2019-03-28 05:58:27

标签: python python-3.x

我正在尝试调用我在代码中定义的函数,但是,这是在说它未定义吗?错误是我有“ 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)

1 个答案:

答案 0 :(得分:1)

您在函数调用后进行了函数声明。请遵循: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']