Home > OS >  Nested for loop in python when range is not a number
Nested for loop in python when range is not a number

Time:10-17

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:

  1. The function range(start, stop, step) has these 3 parameters.
  2. The parameters start and step are optional, but the parameter stop is required.
  3. If you only send one parameter to the function, for example, range(5), the function automatically will set start = 0 and step = 1. Then, range(5) is equal to range(0, 5, 1).
  4. The parameters start, stop and step must be integers. In your case, i is an integer variable that is taking the values 1, 2 and 3, and that's why range(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.

  • Related