2

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?

asked Jan 19, 2013 at 22:57
1
  • 1
    Indentation matters in python; are you sure you put that return where you meant to? Commented Jan 20, 2013 at 0:02

2 Answers 2

13

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.

answered Jan 19, 2013 at 23:10
Sign up to request clarification or add additional context in comments.

2 Comments

that was a typo, the return statement is outside the outer loop. The results remain the same, weird.
@pegausbupt: as DSM points out, that means that you have mixed tabs and spaces. Configure your editor to only use spaces for indentation.
2

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.

answered Jan 20, 2013 at 3:32

1 Comment

thanks! that's exactly my problem. I have some questions: (1) how to see raw code in SO (2) how to avoid mixing white spaces and tabs (3) what is the potential cause for the mixing? i first use notepad++ to write the code then use eclipse to debug it when it went wrong

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.