python- error-prone issues

1. Write a program to see the results:

li = []
for i in range(3):
    def func(x):
        print(x*i)
    li.append(func)

for func in li:
    func(2)

Interview 1.png
result:

4
4
4

It will change the result we want (the code above): We think the result is 0,2,4

# 解析:如果想要将结果变成0,2,4的话,则说明对应的i是随着迭代次数的变化是在变化的,则就需要一个变量去接收这个变量,将变量带入到print中里面,这样每次的i都是在变化的,在print中里面
li = []
for i in range(3):
    def func(x, y=i):  # 接收参数i,
        print(x*y)  # 开辟的内存的函数是不一样的
    li.append(func)

for func in li:
    func(2)

Function 2.png
The result is:

0
2
4

Guess you like

Origin www.cnblogs.com/yangchangjie150330/p/10537498.html