I’m new to Python and I have problem with this code:
def dirs(currentDir):
exe = True
allDirs = os.listdir(currentDir)
print "Directories in %s:" % currentDir
for files in allDirs:
print files
direc = raw_input("Directory name?:")
if direc == "--q":
exe = False
elif currentDir == "/" and exe == True:
theDir = currentDir + direc
dirs(theDir)
elif currentDir != "/" and exe == True:
theDir = currentDir + "/" + direc
dirs(theDir)
print "should return"
Why, when I type –q, prints should return several times?
If directory is /home/username/, it will print three times, if directory is /home/ it will print two times and so on.
I also tried to return in if statement:
if direc == "--q":
return something
But then nothing happens.
Any ideas?
Many thanks!
From what I’ve understood from your comments, this should do the correct thing.
Discussion of the code as provided by you
Please add more information to your post what the code should do. Meanwhile, see here for a semantically equivalent function, it does the exact same thing as your function, but I have removed certain unnecessary things.
Now, as long as you don’t enter
--q, it will never print “should return”.What is the
exevariable for in your program? It doesn’t do anything.If the first
ifclause is executed, non of the others will be excuted, becauseif/elif/.../elseare mutually exclusive clauses. Once you setexe = True,exewill never be accessed again. Thus, you can removeexefrom your code – as it stands – entirely. Perhaps, though, you wanted it to do something different than preventing thoseelifclauses from executing.As for
should returnshould return.--q, you will seeshould returnonce more--q, because it the print statement is after the recursive call.Further, I replaced your directory name handling logic with
os.path.join()which works across all platforms.Here the current behavior:
Recursion
Compare these two functions to see the effect for handling output before and after the recursive call:
Output: