Python Forum

Full Version: Beginner: I need help understanding few lines of a code.
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
num=int(input('Enter the looping number: '))
for i in range(num):
    for j in range(i):
        print(i, end=' ')
    print(" ")
I wrote a program myself to get a pattern of user prompted number. It worked as I hoped. But I came across above given code. I need help in understanding both the print part and how it works to give following output.

Enter the looping number: 5

1
2 2
3 3 3
4 4 4 4
range returns a number that is incremented for each iteration, and starts at zero unless otherwise directed.
So range(5) returns 0, 1, 2, 3, 4 (5 values)

It's syntax is: class range(start, stop[, step])
so you can control what it starts with, when it stops, a skip value
example:
for i in range(1,10,2):
    print(i, end=', ')
print()
Output:
1, 3, 5, 7, 9,
the print part uses end = ' ' which tells print not to add a newline, but substitute what's in the quotes instead.
In your code that is ' '
the final print adds the new line to complete the process.