• Что бы вступить в ряды "Принятый кодер" Вам нужно:
    Написать 10 полезных сообщений или тем и Получить 10 симпатий.
    Для того кто не хочет терять время,может пожертвовать средства для поддержки сервеса, и вступить в ряды VIP на месяц, дополнительная информация в лс.

  • Пользаватели которые будут спамить, уходят в бан без предупреждения. Спам сообщения определяется администрацией и модератором.

  • Гость, Что бы Вы хотели увидеть на нашем Форуме? Изложить свои идеи и пожелания по улучшению форума Вы можете поделиться с нами здесь. ----> Перейдите сюда
  • Все пользователи не прошедшие проверку электронной почты будут заблокированы. Все вопросы с разблокировкой обращайтесь по адресу электронной почте : info@guardianelinks.com . Не пришло сообщение о проверке или о сбросе также сообщите нам.

What Is the Walrus Operator (:=) in Python and Why It's So Useful

Sascha Оффлайн

Sascha

Заместитель Администратора
Команда форума
Администратор
Регистрация
9 Май 2015
Сообщения
1,483
Баллы
155


Back in Python 3.8, a new syntax quietly showed up and turned out to be surprisingly handy. It’s called the walrus operator (:=).
No, it’s not an actual walrus — but it does help you write cleaner code with fewer lines.

What does it actually do?


In short: it lets you assign a value as part of an expression.
Think of it as saying:

“I want to save this value and use it right now — in one go.”
Here’s an example:


while (line := input(">>> ")) != "exit":
print(f"You typed: {line}")




What’s happening here:

  • You ask the user for input (input(...))
  • You store that in the variable line
  • Then immediately check if it’s "exit"

All in one concise line.
No need to write line = input(...) and then if line != "exit" separately.

When should you use it?


Use it when:

  • You want to assign and compare in the same line (e.g., in a while or if)
  • You’re inside a loop or list comprehension
  • You want to avoid repeating the same function call

A word of caution: avoid overusing it. If it makes your code harder to read, it might not be worth the compactness.

Bonus example: reading a file line-by-line


with open("example.txt") as file:
while (line := file.readline()):
print(line.strip())




This is a clean one-liner for looping through file lines without a separate assignment above the loop.

Final thoughts


The walrus operator might look unusual at first, but once you start using it in the right situations, it becomes a natural part of your coding toolkit.
Try it in small places, and you may find it simplifies your logic and keeps your code more expressive.



Источник:

Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.

 
Вверх Снизу