Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Strange stacked range() loop behavior python

(x,y) = 10,10  
for x in range(x-1,x+2):
      for y in range(y-1,y+2):
             print(x,y)

My results… The Y value seems to be increasing each loop it should be 9,10,11 every time.

9 9
9 10
9 11
10 10
10 11
10 12
11 11
11 12
11 13

I have no idea whats causing this. How can I get the desired effect?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

#!/usr/bin/env python3
(x,y) = 10,10
for X in range(x-1,x+2):
      for Y in range(y-1,y+2):
             print(X,Y)

The behaviour has to do with you re-assigning the y variable within your loop. Changing the variables assigned at for: to anything else has given me the behaviour you want:

9 9
9 10
9 11
10 9
10 10
10 11
11 9
11 10
11 11
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading