PYTHON_COMMUNITY_RU Telegram 2557
🧠 Задача на внимание и знание подводных камней в 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
B) 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.

@Python_Community_ru



tgoop.com/Python_Community_ru/2557
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
B) 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.

@Python_Community_ru

BY Python Community


Share with your friend now:
tgoop.com/Python_Community_ru/2557

View MORE
Open in Telegram


Telegram News

Date: |

Private channels are only accessible to subscribers and don’t appear in public searches. To join a private channel, you need to receive a link from the owner (administrator). A private channel is an excellent solution for companies and teams. You can also use this type of channel to write down personal notes, reflections, etc. By the way, you can make your private channel public at any moment. Ng, who had pleaded not guilty to all charges, had been detained for more than 20 months. His channel was said to have contained around 120 messages and photos that incited others to vandalise pro-government shops and commit criminal damage targeting police stations. On Tuesday, some local media outlets included Sing Tao Daily cited sources as saying the Hong Kong government was considering restricting access to Telegram. Privacy Commissioner for Personal Data Ada Chung told to the Legislative Council on Monday that government officials, police and lawmakers remain the targets of “doxxing” despite a privacy law amendment last year that criminalised the malicious disclosure of personal information. The administrator of a telegram group, "Suck Channel," was sentenced to six years and six months in prison for seven counts of incitement yesterday. Avoid compound hashtags that consist of several words. If you have a hashtag like #marketingnewsinusa, split it into smaller hashtags: “#marketing, #news, #usa.
from us


Telegram Python Community
FROM American