简体   繁体   中英

Question about double for loops and ranges

Since I am a beginner to python I was confused as to why j results to this: 0 1 0 1 2 when doing the code below. From my understanding I thought, i represents 0-3 so wouldn't j represents the numbers 0-3 as well.

for i in range(4):
    for j in range(i):
        print(j)

Your first for loop goes from 0 to 3.

So i is 0, then 1, then 2, then 3.

J is going to be 0, then 1, then 2, then 3.

So printing j in range (0) does nothing, because range(0) is nothing.

Then you print j in range(1), which prints 0

Then you print j in range(2) which prints 0, 1

Lastly you print j in range (3) which prints 0, 1, 2

There are 4 iterations of the outer loop, for i set to 0, 1, 2, and 3.

The first one does nothing, as range(0) is an empty sequence.

The second one outputs 0, the only value in range(1) .

The third outputs 0 and 1, the values in range(2) .

The last prints 0, 1, and 2, the values in range(3) .

The key is that the inner call to range uses the current value of i to produce a range of values that does not include i itself.

When you use a for loop on range(x) , It will run its code x times, starting with 0 and incrementing.

for i in range(4) will run 4 times, each with an i value of 0, 1, 2, 3.

When i has a value of 0, for j in range(0) will run 0 times, thus nothing is printed.

When i has a value of 1, for j in range(1) will run once, and print 0.

When i has a value of 2, for j in range(2) will run twice, and print 0, then 1.

Lastly, when i has a value of 3, for j in range(3) will run 3 times, and print 0, 1, 2.

This gives you an output of:

0 1 0 1 2

Debug example:

在此处输入图像描述

In this example for loop for i in range(4) will run while i is smaller than stop value which is in this case 4 (The last run of loop is going to be when i is 3). The default starting value for variable in range function is 0. If you pass two arguments to range function, first will be starting value, and second will be stop value (when variable isn't less then stop value, loop isn't going to run anymore). With every iteration, the starting value will increase by 1. You can change that number by passing third argument to range function. If start and stop value are same, for example 0 and 0, for loop won't run.

It's same with nested for loops, like in your example. Hope I made you for loops little bit easier.

Note: I am not so good at English.

The same way i represents 0-3 ( which is 1 less than the stop arg 4 ); j will take values upto the stop param ( i ) -1 .

On the iteration where i == 3, j will only go upto 2 (ie one less than i ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM