Home > OS >  I came up with this code for pattern generation which is confusing me. What does the second for loop
I came up with this code for pattern generation which is confusing me. What does the second for loop

Time:11-05

rows =6
for num in range(rows):
    for i in range(num): 
        print(num,end=' ')
    print(' ')

The second for loop is doing something to num which I don't understand.

Output:
1  
2 2  
3 3 3  
4 4 4 4  
5 5 5 5 5

CodePudding user response:

The second, or 'inner', for loop isn't doing anything to num besides using it to generate a range of values from 0 to num-1. It also prints out the value of num at each iteration.

The first, or 'outer', for loop is assigning all the values from 0 to rows-1 to the variable num. The value assigned to num by the outer loop at each iteration is used by the inner loop.

CodePudding user response:

The second loop is printing the value of num for the range of num it basically works like this

for i in range(3):
  print(3, end=" ")

which will print out

3 3 3 
rows =6
for num in range(rows):
    for i in range(num): 
      #the second loop iterates over num and each time prints the value num 
        print(num,end=' ')
    print(' ')
  • Related