Penny
Penny

Reputation: 1280

why getting the error of NameError: name 'file' is not defined in python 3

I'm wondering why I got the NameError: name 'file' is not defined in python 3 when calling a function?

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)

and maybe another simple example:

def func(hello):
    print('Hello')

func(hello)

I also got the same error NameError: name 'hello' is not defined. I don't quite understand why this syntax is not compatible with Python3? Thank you very much!

Upvotes: 0

Views: 1943

Answers (1)

Dimitris Fasarakis Hilliard
Dimitris Fasarakis Hilliard

Reputation: 160687

It isn't compatible with any version of Python. hello (or file or any other parameter name) is a name that's only usable within the function body.

When calling func(hello) Python will try and look-up the name hello in the global scope and fail because such a name isn't defined. When Python tries to look-up hello inside the body of func it will succeed because there's a parameter with that name.

The following works:

hello = 'Hello'
def func(hello):
    print(hello)

func(hello)

since hello will be found when the function call to func is made.

Upvotes: 1

Related Questions