sma
sma

Reputation: 897

Weird Python code results

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?

Upvotes: 2

Views: 879

Answers (2)

DSM
DSM

Reputation: 353059

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.

Upvotes: 2

Martijn Pieters
Martijn Pieters

Reputation: 1121904

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.

Upvotes: 13

Related Questions