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
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



tg-me.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


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

Share with your friend now:
tg-me.com/Python_Community_ru/2557

View MORE
Open in Telegram


Python Community Telegram | DID YOU KNOW?

Date: |

What is Telegram Possible Future Strategies?

Cryptoassets enthusiasts use this application for their trade activities, and they may make donations for this cause.If somehow Telegram do run out of money to sustain themselves they will probably introduce some features that will not hinder the rudimentary principle of Telegram but provide users with enhanced and enriched experience. This could be similar to features where characters can be customized in a game which directly do not affect the in-game strategies but add to the experience.

Telegram hopes to raise $1bn with a convertible bond private placement

The super secure UAE-based Telegram messenger service, developed by Russian-born software icon Pavel Durov, is looking to raise $1bn through a bond placement to a limited number of investors from Russia, Europe, Asia and the Middle East, the Kommersant daily reported citing unnamed sources on February 18, 2021.The issue reportedly comprises exchange bonds that could be converted into equity in the messaging service that is currently 100% owned by Durov and his brother Nikolai.Kommersant reports that the price of the conversion would be at a 10% discount to a potential IPO should it happen within five years.The minimum bond placement is said to be set at $50mn, but could be lowered to $10mn. Five-year bonds could carry an annual coupon of 7-8%.

Python Community from us


Telegram Python Community
FROM USA