Telegram Group & Telegram Channel
🐍 Хитрая задача на Python: замыкание + nonlocal

📌 Задача:
Напиши функцию counter(start), которая возвращает функцию-счётчик. Каждый вызов этой функции увеличивает значение на 1.

Пример:


c = counter(10)
print(c()) # 11
print(c()) # 12
print(c()) # 13

d = counter(100)
print(d()) # 101
print(c()) # 14 ← работает независимо


🎯 Подвох:
- Нельзя использовать глобальные переменные
- Нужно использовать замыкание
- Без nonlocal — не заработает

Решение:


def counter(start):
count = start
def inner():
nonlocal count
count += 1
return count
return inner

# Проверка
a = counter(5)
print(a()) # 6
print(a()) # 7

b = counter(100)
print(b()) # 101
print(a()) # 8


🧠 Объяснение подвоха:

- counter возвращает функцию, внутри которой count сохраняется в замыкании
- nonlocal нужен, чтобы изменить внешнюю переменную, а не просто читать её
- Каждое замыкание имеет своё независимое состояние

⚠️ Без nonlocal count, Python создаст локальную count внутри inner(), и UnboundLocalError — гарантирован

🛠️ Применяется в:

• Реализации генераторов состояния
• Мини-хранилищах внутри функций
• Кеширующих функциях и декораторах

@python_job_interview



tg-me.com/python_job_interview/1108
Create:
Last Update:

🐍 Хитрая задача на Python: замыкание + nonlocal

📌 Задача:
Напиши функцию counter(start), которая возвращает функцию-счётчик. Каждый вызов этой функции увеличивает значение на 1.

Пример:


c = counter(10)
print(c()) # 11
print(c()) # 12
print(c()) # 13

d = counter(100)
print(d()) # 101
print(c()) # 14 ← работает независимо


🎯 Подвох:
- Нельзя использовать глобальные переменные
- Нужно использовать замыкание
- Без nonlocal — не заработает

Решение:


def counter(start):
count = start
def inner():
nonlocal count
count += 1
return count
return inner

# Проверка
a = counter(5)
print(a()) # 6
print(a()) # 7

b = counter(100)
print(b()) # 101
print(a()) # 8


🧠 Объяснение подвоха:

- counter возвращает функцию, внутри которой count сохраняется в замыкании
- nonlocal нужен, чтобы изменить внешнюю переменную, а не просто читать её
- Каждое замыкание имеет своё независимое состояние

⚠️ Без nonlocal count, Python создаст локальную count внутри inner(), и UnboundLocalError — гарантирован

🛠️ Применяется в:

• Реализации генераторов состояния
• Мини-хранилищах внутри функций
• Кеширующих функциях и декораторах

@python_job_interview

BY Python вопросы с собеседований


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

Share with your friend now:
tg-me.com/python_job_interview/1108

View MORE
Open in Telegram


telegram Telegram | DID YOU KNOW?

Date: |

At a time when the Indian stock market is peaking and has rallied immensely compared to global markets, there are companies that have not performed in the last 10 years. These are definitely a minor portion of the market considering there are hundreds of stocks that have turned multibagger since 2020. What went wrong with these stocks? Reasons vary from corporate governance, sectoral weakness, company specific and so on. But the more important question is, are these stocks worth buying?

Look for Channels Online

You guessed it – the internet is your friend. A good place to start looking for Telegram channels is Reddit. This is one of the biggest sites on the internet, with millions of communities, including those from Telegram.Then, you can search one of the many dedicated websites for Telegram channel searching. One of them is telegram-group.com. This website has many categories and a really simple user interface. Another great site is telegram channels.me. It has even more channels than the previous one, and an even better user experience.These are just some of the many available websites. You can look them up online if you’re not satisfied with these two. All of these sites list only public channels. If you want to join a private channel, you’ll have to ask one of its members to invite you.

telegram from id


Telegram Python вопросы с собеседований
FROM USA