-4

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
Gino Mempin
  • 25,369
  • 29
  • 96
  • 135
CyberEvil
  • 1
  • 1

1 Answers1

0
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
"""
Tario You
  • 347
  • 2
  • 7
  • may I know why it only takes the last value in the item and python not printing whole value – CyberEvil Jan 27 '23 at 08:01
  • 1
    @CyberEvil What do you mean by whole value? – Tario You Jan 27 '23 at 09:39
  • whole value means that why it doesn't print 1,2,3 for another time – CyberEvil Jan 27 '23 at 12:07
  • As I explained at the first iteration, item = 1, then item = 2, then item = 3, never was item equal to (1, 2, 3), so it will not print 1, 2, 3 again. If you want to print it another time you can do this ```for i in range(2): for item in (1, 2, 3): print(item) ``` – Tario You Jan 27 '23 at 16:57