Can't get my head around Loops and nested loops

Hey guys, I’m new to python and in the past 2 days, I’ve been trying to learn how to code python.
after getting used to some topics, I came across loops and nested loops which I find really confusing especially when there’s a loop inside a loop.

One exercise I tried to get my head around is constructing a pattern using for loops.
Here is an example:

n=5;
for i in range(n):
    for j in range(i):
        print ('* ', end="")
    print('')

for i in range(n,0,-1):
    for j in range(i):
        print('* ', end="")
    print('')
	

which gives an output:

* 
* * 
* * * 
* * * * 
* * * * * 
* * * * 
* * * 
* * 
*

I can’t get my head around how it’s doing this. I know that ‘i’ goes through the range n = 1,2,3,4,5. but what does it mean when j loops to the range i?
regarding range(n,0,-1). I assume it’s n =5 to range 0 and increment by -1?

also is there another way of doing this so that it looks easier for a beginner or is ‘readable’?

However, I do understand the output when comparing 2 lists together such as this:

list1= [1,2,3,4]
list2= ['a','b','c','d']

for i in list1:
  for j in list2:
    print(i,j)

giving an output of

1 a
1 b
1 c
1 d
2 a
2 b
2 c
2 d
3 a
3 b
3 c
etc..

I just can’t get my head around what happens when there’s no lists to compare

Hello @gianmaraon2959200050, welcome to the forums!

This sets up a loop looping through 5 times (range(5)).

This loops through the range of i. So when i is 1, it loops once, when i is 2, it loops twice, etc.

This print * for every iteration of this loop:

So for when i is 4, you would expect this:

*
*
*
*

The

however, means that the end is an empty string, and not a new line, thus making the

****

shape.

This loop does the same thing, just in reverse.

This is correct. i starts at 5, giving the *****, then decrements by 1 (the -1) until it reaches 1.

I hope this helps!

2 Likes

Hi, thank you for the explanation, makes total sense now :slight_smile:

1 Like