Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Weird Python code results

Tags:

python

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?

like image 417
sma Avatar asked Apr 23 '26 05:04

sma


1 Answers

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.

like image 104
Martijn Pieters Avatar answered Apr 24 '26 17:04

Martijn Pieters



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!