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

后端 未结 1 786
名媛妹妹
名媛妹妹 2020-11-29 11:59

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         


        
相关标签:
1条回答
  • 2020-11-29 12:37

    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.

    0 讨论(0)
提交回复
热议问题