From what I've understood from your comments, this should do the correct thing.
def dirs(currentDir):
allDirs = os.listdir(currentDir)
print "Directories in %s:" % currentDir
for files in allDirs:
print files
direc = raw_input("Directory name?:")
if direc != "--q":
theDir = os.path.join(currentDir, direc)
return dirs(theDir)
else:
return currentDir
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.
def dirs(currentDir):
allDirs = os.listdir(currentDir)
print "Directories in %s:" % currentDir
for files in allDirs:
print files
direc = raw_input("Directory name?:")
if direc != "--q":
theDir = os.path.join(currentDir, direc)
dirs(theDir)
print "should return"
Now, as long as you don't enter --q, it will never print "should return".
What is the exe variable for in your program? It doesn't do anything.
If the first if clause is executed, non of the others will be excuted, because if/elif/.../else are mutually exclusive clauses. Once you set exe = True, exe will never be accessed again. Thus, you can remove exe from your code – as it stands – entirely. Perhaps, though, you wanted it to do something different than preventing those elif clauses from executing.
As for should return
- You will always see at least one
should return.
- For every time you don't enter
--q, you will see should return once more
- They all print after you enter
--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:
>>> dirs(r"C:\Python27")
Directories in C:\Python27:
DLLs
Doc
include
Lib
libs
LICENSE.txt
NEWS.txt
python.exe
pythonw.exe
README.txt
Removesetuptools.exe
Scripts
setuptools-wininst.log
tcl
Tools
w9xpopen.exe
Directory name?:Doc
Directories in C:\Python27\Doc:
python273.chm
Directory name?:--q
should return
should return
Recursion
Compare these two functions to see the effect for handling output before and after the recursive call:
def string_foo(text):
first, rest = text[0], text[1:]
print first
if rest:
string_foo(rest)
def string_bar(text):
first, rest = text[0], text[1:]
if rest:
string_foo(rest)
print first
Output:
>>> string_foo("Hello")
H
e
l
l
o
>>> string_bar("Hello")
o
l
l
e
H