简体   繁体   English

缩进如何影响Python中for循环内变量的scope?

[英]How does indentation affect the scope of the variable inside a for loop in Python?

I print an item twice with indentation, and it prints the values of the item in iterated format.我用缩进打印一个项目两次,它以迭代格式打印项目的值。 But when I print an item without indentation (I mean after the loop ends) it only prints the last value of item.但是当我打印一个没有缩进的项目时(我的意思是在循环结束后)它只打印项目的最后一个值。

Here in the code it is 3 .在代码中它是3 Why?为什么?

for item in (1,2,3):
  print(item)
  print(item)
print(item)

output: output:

1
2
3  
1
2
3
3
for item in (1, 2, 3):
    print(item)

print()

print(item)  # this prints 3 because it is the last number item was assigned to

"""
Iteration 1: item = 1
Iteration 2: item = 2
Iteration 3: item = 3
print(item) # prints 3
"""

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

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