I have a hard time understanding this:
for i in range(1, 4):
for j in range(i):
print(i)
when the inner loop's range is a number I understand it, but on the code above, the inner loop is running in range(i). What does that mean? Thank you.
CodePudding user response:
Let's go step by step:
- The function
range(start, stop, step)
has these 3 parameters. - The parameters
start
andstep
are optional, but the parameterstop
is required. - If you only send one parameter to the function, for example,
range(5)
, the function automatically will setstart = 0
andstep = 1
. Then,range(5)
is equal torange(0, 5, 1)
. - The parameters
start
,stop
andstep
must be integers. In your case,i
is an integer variable that is taking the values1
,2
and3
, and that's whyrange(i)
is valid.
CodePudding user response:
i
is a variable set by the loop it is inside of. i
is the number iterating (that's why it's commonly called i). j then iterated through all the numbers up to i
.
For example, range(1,4)
could be 3 sizes of sweets where each size up has one more sweet (1 packet with 1 sweet, 1 packet with 2 sweets, 1 packet with 3 sweets). The second loop iterates through each of the sweets in the packet (where packet is i
and sweet is j
). You're then printing the packet you ate.