-4

this question is based on this other one: Nested Loop Python

One of the answer is

for i in range(1, 10):
    for j in range(i):
        print(i, end='')
    print()

I don't understand why after the print(i, end = ' ') statement Python then runs the print() statement. In other words, since print() is not in the nested loop, shouldn't this code be only run after the nested j loop is completed?

Drise
  • 4,310
  • 5
  • 41
  • 66
Alan
  • 157
  • 8

3 Answers3

0

It is only run after the nested loop. Looking at the output from the post you referenced, the program starts with 1, prints one 1 without a newline, then exits the nested loop, then prints the newline. Then it enters the nested loop with 2, loops twice (prints a 2 without a newline, then prints a second two without a newline), then exits the loop and prints a newline.

0

The print() is indented to be a part of the' i' for loop. So every time that 'i' for block runs, the' j 'for happens THEN the print() takes the cursor to the next line

uhexos
  • 383
  • 4
  • 19
0

The print() statement is executed after the nested j loop. It has been indented to make it a part of the outer loop i.

What print() statement is actually doing here?

It is used to move the cursor to the next line after each row is printed.

Understand it like this:

for i in range(0,range1):

(indentation) for j in range(0,range2):

(indentation)(indentation) print(i, end='') //loop j ends

(indentation) print() //part of outer loop i