Can I anyone tell me why the following code generates such results?
def weird(s):
print s
for ii in range(len(s)):
for jj in range(ii, len(s)+1):
print ii, jj
return
if __name__=="__main__":
ss="acaacb"
weird(ss)
results:
acaacb
0 0
0 1
0 2
0 3
0 4
0 5
0 6
Should the value of ii iterate through 0 to 5?
-
1Indentation matters in python; are you sure you put that return where you meant to?Eric Lippert– Eric Lippert2013年01月20日 00:02:51 +00:00Commented Jan 20, 2013 at 0:02
2 Answers 2
No, you placed a return statement inside of the outer for loop. At the end of the first iteration, you exit the function. That's what a return statement does; it ends the function regardless of what loop construct you are currently executing.
Remove the return statement and the loop will continue to run all the way to i = 5.
2 Comments
Looking at your raw code paste, something seems strange with your indentation, probably due to mixing tabs and spaces (it's hard to be sure because sometimes whitespace doesn't survive being pasted into SO in the same state it started in). Looking at each line:
'\n'
'\n'
' def weird(s):\n'
' print s\n'
' \n'
' for ii in range(len(s)):\n'
' for jj in range(ii, len(s)+1):\n'
' print ii, jj\n'
' \n'
' return\n'
'\n'
' if __name__=="__main__":\n'
'\t ss="acaacb"\n'
'\t weird(ss)\n'
Whitespace problems can lead to strange errors where code actually isn't as indented as you think it is. You can test this theory by running your program using
python -tt your_program_name.py
and then switch to using four spaces instead of tabs.