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

How to Invest in Bitcoin?

Like a stock, you can buy and hold Bitcoin as an investment. You can even now do so in special retirement accounts called Bitcoin IRAs. No matter where you choose to hold your Bitcoin, people’s philosophies on how to invest it vary: Some buy and hold long term, some buy and aim to sell after a price rally, and others bet on its price decreasing. Bitcoin’s price over time has experienced big price swings, going as low as $5,165 and as high as $28,990 in 2020 alone. “I think in some places, people might be using Bitcoin to pay for things, but the truth is that it’s an asset that looks like it’s going to be increasing in value relatively quickly for some time,” Marquez says. “So why would you sell something that’s going to be worth so much more next year than it is today? The majority of people that hold it are long-term investors.”

Export WhatsApp stickers to Telegram on iPhone

You can’t. What you can do, though, is use WhatsApp’s and Telegram’s web platforms to transfer stickers. It’s easy, but might take a while.Open WhatsApp in your browser, find a sticker you like in a chat, and right-click on it to save it as an image. The file won’t be a picture, though—it’s a webpage and will have a .webp extension. Don’t be scared, this is the way. Repeat this step to save as many stickers as you want.Then, open Telegram in your browser and go into your Saved messages chat. Just as you’d share a file with a friend, click the Share file button on the bottom left of the chat window (it looks like a dog-eared paper), and select the .webp files you downloaded. Click Open and you’ll see your stickers in your Saved messages chat. This is now your sticker depository. To use them, forward them as you would a message from one chat to the other: by clicking or long-pressing on the sticker, and then choosing Forward.

telegram from us


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