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