Python function with default argument inside loop

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

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

Does it print 4 every time? Can someone help me figure this out.

+4
source share
3 answers

You redefine test4 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)

therefore you only have 1 test()last.

+8
source

The function is testredefined on each iteration of the loop.

By the time the loop completes, it's testsimple:

def test(i=4):
    print(i)
+3
source

script , for 4

test(), 4

,

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

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

:

0
1
2
3
4
test
4
test
4
test
4
test
4
test
4
+3

Source: https://habr.com/ru/post/1649378/


All Articles