0

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!

1
  • 1
    Python should know what is hello? define hello then use it in the function. Commented Mar 13, 2017 at 10:51

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you and yes that makes sense!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.