嵌套循环使用相同的变量,在内循环体之后重复使用¶
ID: py/nested-loops-with-same-variable-reused
Kind: problem
Security severity:
Severity: error
Precision: very-high
Tags:
- maintainability
- correctness
Query suites:
- python-security-and-quality.qls
在 Python 中,变量具有函数级作用域,这意味着如果两个变量在同一个作用域中具有相同的名称,它们实际上是一个变量。因此,如果嵌套循环中的目标变量具有相同的名称,实际上它们共享一个变量。此类循环很难理解,因为内循环将修改外循环的目标变量。如果在内循环终止后使用循环变量,这可能会导致意外行为。
建议¶
重命名内循环变量。
示例¶
此示例展示了一个处理一系列数字列表的函数。它打印出每个列表中的最大元素。在第一个版本中,变量 x
被内循环覆盖,导致错误的输出。在第二个函数中,通过重命名内循环变量来修复错误,以防止其覆盖外循环变量。
def largest_elements(l):
for x in l:
maxnum = 0
for x in x:
maxnum = max(x, maxnum)
# The outer loop variable x has now been overwritten by the inner loop.
print "The largest element in the list", x, "is", maxnum
def largest_elements_correct(l):
for x in l:
maxnum = 0
for y in x:
maxnum = max(y, maxnum)
print "The largest element in the list", x, "is", maxnum
参考¶
Python 语言参考:The for statement.
Python 教程:for statements.