首页 > 解决方案 > 在 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.

名称错误发生在代码的最后一行。

标签: pythonfunction

解决方案


newNameList仅在 的范围内定义function2。由于该print语句未在同一级别缩进,因此function2对其newNameList不可见。在顶级作用域中定义的三个变量是ListofNames1ListofNames1names。这些是可以function2print语句中传递的仅有的三个变量。


推荐阅读