Telegram Group & Telegram Channel
🧠 Python-задача на внимательность и знание подводных камней

Что выведет этот код?


def make_funcs():
funcs = []
for i in range(3):
def wrapper(x=i):
return lambda: x
funcs.append(wrapper())
return funcs

a, b, c = make_funcs()
print(a(), b(), c())


Варианты ответа:

A)0 1 2
В) 2 2 2
C)0 0 0
D)Ошибка на этапе выполнения

Ответ: 0 1 2

📘 Объяснение:
🔹 Цикл for i in range(3) проходит по значениям 0, 1, 2.

🔹 В каждой итерации вызывается wrapper(x=i) — это копирует текущее значение i в локальную переменную x.

🔹 Затем возвращается lambda: x, которая запоминает это конкретное значение x.

🔹 В итоге:

a() → 0

b() → 1

c() → 2

Если бы мы не использовали x=i по умолчанию, а писали просто lambda: i, все функции замкнули бы одну и ту же переменную i, и на момент вызова она бы уже была равна 3.


@pythonl



tg-me.com/pythonl/4734
Create:
Last Update:

🧠 Python-задача на внимательность и знание подводных камней

Что выведет этот код?


def make_funcs():
funcs = []
for i in range(3):
def wrapper(x=i):
return lambda: x
funcs.append(wrapper())
return funcs

a, b, c = make_funcs()
print(a(), b(), c())


Варианты ответа:

A)0 1 2
В) 2 2 2
C)0 0 0
D)Ошибка на этапе выполнения

Ответ: 0 1 2

📘 Объяснение:
🔹 Цикл for i in range(3) проходит по значениям 0, 1, 2.

🔹 В каждой итерации вызывается wrapper(x=i) — это копирует текущее значение i в локальную переменную x.

🔹 Затем возвращается lambda: x, которая запоминает это конкретное значение x.

🔹 В итоге:

a() → 0

b() → 1

c() → 2

Если бы мы не использовали x=i по умолчанию, а писали просто lambda: i, все функции замкнули бы одну и ту же переменную i, и на момент вызова она бы уже была равна 3.


@pythonl

BY Python/ django


Warning: Undefined variable $i in /var/www/tg-me/post.php on line 283

Share with your friend now:
tg-me.com/pythonl/4734

View MORE
Open in Telegram


Python django Telegram | DID YOU KNOW?

Date: |

Telegram today rolling out an update which brings with it several new features.The update also adds interactive emoji. When you send one of the select animated emoji in chat, you can now tap on it to initiate a full screen animation. The update also adds interactive emoji. When you send one of the select animated emoji in chat, you can now tap on it to initiate a full screen animation. This is then visible to you or anyone else who's also present in chat at the moment. The animations are also accompanied by vibrations. This is then visible to you or anyone else who's also present in chat at the moment. The animations are also accompanied by vibrations.

Mr. Durov launched Telegram in late 2013 with his brother, Nikolai, just months before he was pushed out of VK, the Russian social-media platform he founded. Mr. Durov pitched his new app—funded with the proceeds from the VK sale—less as a business than as a way for people to send messages while avoiding government surveillance and censorship.

Python django from de


Telegram Python/ django
FROM USA