Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python function with default argument inside loop

for i in range(5):
   def test(i=i):
      print(i)

test()
test()
test()
test()
test()

This prints 4 every time? Can someone help me understanding this.

like image 858
abs Avatar asked Dec 07 '22 21:12

abs


2 Answers

The function test is redefined every iteration of the loop.

By the time the loop is done, test is simply:

def test(i=4):
    print(i)
like image 34
DeepSpace Avatar answered Dec 10 '22 10:12

DeepSpace


You redefine the test 4 times:

same as:

#define test
def test(i = 0):
    print(i)

#redefine test
def test(i = 1):
    print(i)

#redefine test
def test(i = 2):
    print(i)

#redefine test
def test(i = 3):
    print(i)

#redefine test
def test(i = 4):
    print(i)

so you have only 1 test() the last one.

like image 140
Szabolcs Dombi Avatar answered Dec 10 '22 10:12

Szabolcs Dombi