Why am I getting a NameError when I try to call my function?

百般思念 提交于 2019-11-26 14:49:14

问题


This is my code:

import os

if os.path.exists(r'C:\Genisis_AI'):
    print("Main File path exists! Continuing with startup")
else:
    createDirs()

def createDirs():
    os.makedirs(r'C:\Genisis_AI\memories')

When I execute this, it throws an error:

File "foo.py", line 6, in <module>
    createDirs()
NameError: name 'createDirs' is not defined

I made sure it's not a typo and I didn't misspell the function's name, so why am I getting a NameError?


回答1:


You can't call a function unless you've already defined it. Move the def createDirs(): block up to the top of your file, below the imports.

Some languages allow you to use functions before defining them. For example, javascript calls this "hoisting". But Python is not one of those languages.


Note that it's allowable to refer to a function in a line higher than the line that creates the function, as long as chronologically the definition occurs before the usage. For example this would be acceptable:

import os

def doStuff():
    if os.path.exists(r'C:\Genisis_AI'):
        print("Main File path exists! Continuing with startup")
    else:
        createDirs()

def createDirs():
    os.makedirs(r'C:\Genisis_AI\memories')

doStuff()

Even though createDirs() is called on line 7 and it's defined on line 9, this isn't a problem because def createDirs executes before doStuff() does on line 12.



来源:https://stackoverflow.com/questions/50237122/why-am-i-getting-a-nameerror-when-i-try-to-call-my-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!