why getting the error of NameError: name 'file' is not defined in python 3
why getting the error of NameError: name 'file' is not defined in python 3
我想知道为什么调用函数时出现 NameError: name 'file' is not defined in python 3?
def func(file):
for file in os.listdir(cwd):
if file.endswith('.html'):
f = open(file, "r+")
....
f = open(file, "w")
f.write(text)
f.close()
func(file)
也许还有另一个简单的例子:
def func(hello):
print('Hello')
func(hello)
我也遇到同样的错误 NameError: name 'hello' is not defined。
我不太明白为什么这个语法不兼容Python3?
非常感谢!
它与 Python 的任何版本都不兼容。 hello
(或file
或任何其他参数名称)是一个只能在函数体内使用的名称。
当调用 func(hello)
时,Python 将尝试在 全局范围 中查找名称 hello
并失败,因为这样的名称未定义。当 Python 尝试在 func
的正文中查找 hello
时,它将成功,因为有一个具有该名称的参数。
以下作品:
hello = 'Hello'
def func(hello):
print(hello)
func(hello)
因为 hello
将在调用 func
的函数时找到。
我想知道为什么调用函数时出现 NameError: name 'file' is not defined in python 3?
def func(file):
for file in os.listdir(cwd):
if file.endswith('.html'):
f = open(file, "r+")
....
f = open(file, "w")
f.write(text)
f.close()
func(file)
也许还有另一个简单的例子:
def func(hello):
print('Hello')
func(hello)
我也遇到同样的错误 NameError: name 'hello' is not defined。 我不太明白为什么这个语法不兼容Python3? 非常感谢!
它与 Python 的任何版本都不兼容。 hello
(或file
或任何其他参数名称)是一个只能在函数体内使用的名称。
当调用 func(hello)
时,Python 将尝试在 全局范围 中查找名称 hello
并失败,因为这样的名称未定义。当 Python 尝试在 func
的正文中查找 hello
时,它将成功,因为有一个具有该名称的参数。
以下作品:
hello = 'Hello'
def func(hello):
print(hello)
func(hello)
因为 hello
将在调用 func
的函数时找到。