简体   繁体   English

嵌套循环输出混乱

[英]Nested loop output confusion

for i in range(2):
    for j in range(2):
        print(i, j, end='')

Hey guys so im just having problems understanding this concept of nested loops. 大家好,我在理解嵌套循环的概念时遇到了问题。 The output when I run the program is: 0 00 11 01 1 运行程序时的输出为:0 00 11 01 1

I cant figure out why the output is the way it is. 我不明白为什么输出是这样。 Could anybody give me a step by step explanation of the order in which this is executed? 有人可以逐步解释执行顺序吗?

Thanks 谢谢

i = 0 and j = 0 i = 0和j = 0

it will print 0 0, here end is '', means no space 它会打印0 0,这里的结尾是“”,表示没有空格

now i = 0 and j=1 现在我= 0和j = 1

it will print 0 00 1 它将打印0 00 1

now i=1 j=0 现在i = 1 j = 0

it will print 0 00 11 0 它将打印0 00 11 0

now i=1 and j=1 现在i = 1和j = 1

it will print 0 00 11 01 1 它将打印0 00 11 01 1

Does this slight reformatting of your output help: 重新格式化您的输出是否有助于:

0 00 11 01 1   ==>  0 0 | 0 1 | 1 0 | 1 1
                    i j   i j   i j   i j

You have two loops in your program. 您的程序中有两个循环。 One is outer and another one is inner loop. 一个是外部循环,另一个是内部循环。 So this is how code is working. 这就是代码的工作方式。 First of all following code is executed 首先执行以下代码

for i in range(2):

This puts value 0 in i. 这将值0放入i。 Now it enters to inner loop. 现在进入内循环。 So following code is executed 所以执行以下代码

for j in range(2):

This puts value 0 in j. 这会将值0放入j。 Now the following code executes 现在执行以下代码

print(i,j,end='')

This gives the output as i and j both have 0 value. 这给出了输出,因为i和j均为0。

0 0

In programming language inner loop are completed first. 在编程语言中,内部循环首先完成。 So following code will execute again 因此,以下代码将再次执行

for j in range(2):

This will set value of j as 1 这会将j的值设置为1

Now j is 1 and i is still 0 So output will look like 现在j是1而我仍然是0所以输出看起来像

0 00 1

(Note: first 0 0 is the previous output) (注意:前0 0是前一个输出)

Now the following code is finished 现在下面的代码完成了

for j in range(2):

Its finished at j's value 1 because range(2) means value will start from 0 to 1. 它以j的值1结束,因为range(2)表示值将从0开始到1。

Now the following code will execute. 现在将执行以下代码。

for i in range(2):

and i value will become 1. 我的价值将变成1。

Now the inner loop will run again. 现在,内部循环将再次运行。

for j in range(2):

This will set value of j again 0 and in the next iteration 1. 这将再次将j的值设置为0,并在下一次迭代1中设置。

So the final output looks like 所以最终输出看起来像

0 00 11 01 1

Modify your code as below and It will remove the confusion: 如下修改您的代码,它将消除混乱:

>>> for i in range(2):
    for j in range(2):
        print(i, j, sep='', end=' ')


00 01 10 11

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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