Python两个循环每次运行一次迭代

时间:2015-07-14 15:03:59

标签: python python-3.4

我正在尝试使用Python args和kwargs进行一些实验并遇到意想不到的问题。我的代码是:

def argsandkwargs(*args,**kwargs):
    sum = 0
    for arg in args:
        sum += arg
        print(sum)
    for i, j in kwargs.items():
        print('i is ' + i + ' and j is ' + j)

argsandkwargs(5,2,3,6,3,7,actor='RDJ',movie='Iron Man')

输出结果为:

5
i is movie and j is Iron Man
i is actor and j is RDJ
7
i is movie and j is Iron Man
i is actor and j is RDJ
10
i is movie and j is Iron Man
i is actor and j is RDJ
16
i is movie and j is Iron Man
i is actor and j is RDJ
19
i is movie and j is Iron Man
i is actor and j is RDJ
26
i is movie and j is Iron Man
i is actor and j is RDJ

如果args和kwargs循环是分开的,我希望看到:

5
7
10
16
19
26
5
i is movie and j is Iron Man
i is actor and j is RDJ

为什么python会以这种方式运行?看起来它从每个循环一次运行一次迭代,而不是每个循环中的所有迭代,然后再移动到下一个循环。

1 个答案:

答案 0 :(得分:0)

  

仔细检查您是否没有混合空格和标签。 Python认为第二个for循环缩进到与它上面的print语句相同的级别。

谢谢@Kevin,我有第一个循环的空格,第二个循环缩进;并没有意识到python与这些区别开来。