Python task explanation

Dear friends, I’m practicing range() function.

This is the task: “Print the following number pattern using Python range() and for loop.”
1
2 2
3 3 3

This is the solution:

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

Can anyone explain me how it works?

Start with this code:

for num in range(4):
    print("num =", num)

This will print:

num = 0
num = 1
num = 2
num = 3

Now try this code:

for num in range(4):
    print("num =", num)
    for i in range(num):
        print("i =", i)

which will print:

num = 0
num = 1
i = 0
num = 2
i = 0
i = 1
num = 3
i = 0
i = 1
i = 2

Does that help? Let’s break it down some more.

for i in range(3) gives us i = 0, 1, 2.

for i in range(2) gives us i = 0, 1.

for i in range(1) gives us i = 0.

for i in range(0) gives us nothing at all.

So we can see that range(num) starts at 0 and finishes at one less
than num; if num happens to be 0, then the loop finishes before it
starts.

So the double for-loop gives us:

  • on the first loop, num is 0 and the inner loop runs zero times;

  • on the second loop, num is 1 and the inner loop runs one time;

  • on the third loop, num is 2 and the inner loop runs two times;

  • on the fourth loop, num is 3 and the inner loop runs three times.

Now let’s think about this:

for num in range(4):
    for i in range(num):
        print(num, end=" ")
  • on the first loop, num is 0 and the inner loop runs zero times, so
    nothing is printed;

  • on the second loop, num is 1 and the inner loop runs one time, so “1”
    is printed one time;

  • on the third loop, num is 2 and the inner loop runs two times, so “2”
    is printed two times;

  • on the fourth loop, num is 3 and the inner loop runs three times, so
    “3” is printed three times.

The only mystery remaining is that end=" ". Let’s try it:

print("Hello")
print("World")

which gives us:

Hello
World

Now try this:

print("Hello", end="---")
print("World")

which gives us:

Hello---World

What do you expect end=" " to give?

1 Like