Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Scoped variables.
#1
Hi,

I'm trying out the code below but need help in understanding why the
it's printing 3 3 3 rather than 1 2 3.

list_of_printers = []
for i in [1, 2, 3]:
    def printer():
        print(i)
    list_of_printers.append(printer)

for func in list_of_printers:
    func()
Thanks in advance for any help.
Reply
#2
When appending printer to the list of printers it is only adding the function name, at this point i does not exist in the function.
When the func is called from the list of printers it gets the value from i which will be the last value from the loop
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020