Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python – Variable won't print? (Trying to get variable outside of while/if, etc.)

I have this code:

global dir_name
dir_name = ''

def generateDirectoryName(newpath, x=0):
    while True:
        dir_name = (newpath + ('_' + str(x) if x != 0 else '')).strip()
        if not os.path.exists(dir_name):
            os.mkdir(dir_name)
            #1
            #print(dir_name)
            return dir_name
        else:
            x = x + 1


def createDirectory():
    generateDirectoryName(newpath)


def main():
    cwd = os.getcwd()
    createDirectory()

#2
print(dir_name)

main()

#3
print(dir_name)

When I try the code, the two prints at the end (labelled with comments 2 and 3 don’t appear to have any effect. However, if I uncomment the print inside the function (at comment 1), it will show the dir_name value. Why does this happen – why can’t I access dir_name outside the function? How can I fix the problem?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

dir_name is a local variable in your function. In order to change it to global you have to use global dir_name inside the function. As far as printing goes, dir_name is actually getting printed at 2 and 3 but is just an empty string. Also, you dont have to return dir_name as you’re not assigning the return value of generateDirectoryName(newpath, x=0) to anything in createDirectory. Here is an updated version of your code:

dir_name = ''

def generateDirectoryName(newpath, x=0):
    global dir_name
    while True:
        dir_name = (newpath + ('_' + str(x) if x != 0 else '')).strip()
        if not os.path.exists(dir_name):
            os.mkdir(dir_name)
           #1
            #print(dir_name)
            return
        else:
            x = x + 1


def createDirectory():
    generateDirectoryName(newpath)


def main():
    cwd = os.getcwd()
    createDirectory()

#2 (This will still print an empty string)
print(dir_name)

main()

#3 (This will print whatever is printed in #1)
print(dir_name)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading