Nested loop | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Nested loop

i cant understand the result: for x in range(1,8): for y in range (1,x): print(x,y)

8th Jun 2018, 10:18 PM
Mohamed Rashidey Hasan
Mohamed Rashidey Hasan - avatar
1 Answer
+ 2
I'll just try to break this down the best I can: In your first loop, you're setting a variable x to start with a set value of 1, increasing by 1 while running the code within the block before each iteration. Within the loop, you set another for loop which contains the variable y starting at a set value of 1. For everytime that x is set to a value, the upper limit (the number that y will stop at in the second for loop) will become the value of x. With the second for loop now having both a lower limit and upper limit, y will be set to a variable, running the code within it before increasing until it is equal to the value of x. Once it reaches that value, x will increase by one and restart the cycle. So, if you were in the iteration where x equals 3, then the upper limit of the second for loop would be 3. This would make y start at 1, printing out the value of both itself and x until it equals the value of x. Once it does so, x will then become 4, and the loop will continue until x equals 8. Hope this helped!
9th Jun 2018, 2:35 AM
Faisal
Faisal - avatar