python - 在 Python 中使用函数的新手
问题描述
我试图理解为什么newNameList
没有定义:
ListofNames1 = ['Mark', 'Andrew']
ListofNames2 = ['Anjela', 'Lora']
names = ListofNames1
def greeting(names):
newNameList = []
for item in names:
newNameList.append(str(names))
return (names)
print(greeting(names))
def function2(newNameList):
for each in newNameList:
newNameList2.append(newNameList.upper())
return (newNameList2)
print(function2(newNameList))
输出
['Mark', 'Andrew']
...
NameError: name 'newNameList' is not defined.
名称错误发生在代码的最后一行。
解决方案
newNameList
仅在 的范围内定义function2
。由于该print
语句未在同一级别缩进,因此function2
对其newNameList
不可见。在顶级作用域中定义的三个变量是ListofNames1
、ListofNames1
和names
。这些是可以function2
在print
语句中传递的仅有的三个变量。
推荐阅读
- cmake - CMake:如何使用 Autotools 构建外部项目?
- javascript - 涉及异步代码的失败测试在任意条件下失败
- python - 如何在烧瓶中使用 Python 生成器
- laravel - laravel - 制作一个脚本以自动将请求作为测试发送到所有 api
- git - 当我有多个 github 帐户时,通过 ssh 发生 Git 权限错误
- javascript - IE 不支持 JavaScript 对象属性?
- asp.net - 如何从 RDLC 报告中的数据集中获取一组特定单元格
- excel - 有没有办法在 Visual Basic 中编辑 excel VBA 宏
- sql - SQL 代码风格。我应该使用 INNER 关键字吗
- boost - BOOST_INCLUDEDIR 和 BOOST_LIBRARYDIR 不同时的 find_package(Boost) 错误