Can You Spot What’s Wrong With This Code? #python #coding #programming #pythontips

Can You Spot What’s Wrong With This Code? #python #coding #programming #pythontips

Machine-readable: Markdown · JSON API · Site index

Поделиться Telegram VK Бот
Транскрипт Скачать .md
Анализ с AI

Оглавление (1 сегментов)

Segment 1 (00:00 - 01:00)

Can you spot what's wrong with this code? We have three functions that greet the user in English, French, and Spanish. To clean things up, we move the greeting messages to a separate dictionary, and each function just looks up its greeting. Calling these functions gives you exactly the output you would expect. And now we refactor this code. We loop over the greeting messages, create one function per language, and store them in a dedicated dictionary. Nice and clean. Once again, we call these functions. And what happened here? Every single output message is in Spanish. Can you spot what went wrong? This phenomenon is known as late binding. Our greet function here depends on an external variable greeting. Python doesn't lock in the value of greeting when the function is created. As you might expect, it waits until the function is called. But by the end of our for loop, the variable greeting is set to hola in Spanish, which is why all the function calls print the same greeting message. The fix here is to make the variable greeting local. For example, make it a default argument to the function greet. Calling the greeting functions now will work just as expected.

Другие видео автора — Visually Explained

Ctrl+V

Экстракт Знаний в Telegram

Экстракты и дистилляты из лучших YouTube-каналов — сразу после публикации.

Подписаться

Дайджест Экстрактов

Лучшие методички за неделю — каждый понедельник