python - for循环中变量的访问范围

标签 python

在我在这里发布这个问题之前,我已经搜索过 SO,希望 这不是重复的。

def print_me():
    a_list = range(1, 10)
    for idx, aa in enumerate(a_list):
        pass
    print(idx)

if __name__ == '__main__' : print_me()

输出如下:

8

我来自 C++ 世界,无法弄清楚为什么 idx 仍然在范围内 代码在 for 循环之外?

谢谢

最佳答案

for 循环不创建任何作用域。这就是原因。

在此特定代码中,idxprint_me 函数的局部变量。

来自 the docs :

以下是 block :

  • 一个模块
  • 一个函数体
  • 类定义

更新

生成器表达式也有自己的作用域。

As of Python 3.0列表理解也有自己的范围。

关于python - for循环中变量的访问范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7715297/

相关文章:

python - 来自内联模型的循环查询集

python - 查找 nan 填充数组的固定长度连续区域(无重叠)

python - 在 Pandas 的下一个 K 连续行中找到最高值?

python - 在 Python 中使用正则表达式删除数据框的部分列名

python - Python 中 unicode 的问题

python - QuickSort 对于低范围数据工作缓慢

python - 如何使用python在字符串中间插入一个或多个字符?

php - Python 包到 PHP 包

python - OpenCV:selectROI返回零元组

Python 使用 numpy\pandas 选择多个范围