简体   繁体   中英

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 . Why?

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

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
"""

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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