python - 已定义函数中未解析的引用
问题描述
我试图调用我在代码中定义的函数,但是,它是说它没有定义?错误是我有“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)
解决方案
你在函数调用之后做了函数声明。请关注: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']
推荐阅读
- c# - 如何将 MIDI 从 Unity 发送到外部 VST
- java - Appium 框架中的非法参数异常
- git - 从文件中删除所有未跟踪
- html - CSS 正确:-50 并且过渡不起作用
- java - JavaFX 2 秒后在 GridPane 上添加行
- python - 错误:ImportError: cannot import name 'doSum' from 'Sum' (G:\firstpy\Sum.py)
- javascript - 意外的令牌 = import/no-named-as-default eslint 错误
- shell - 使用shell脚本awk将另一个字段上的函数结果附加到csv中
- python - 如何在 keras 神经网络中进行简单的数据召回
- java - LazyCsrfTokenRepository$SaveOnAccessCsrfToken 无法转换为 CsrfToken