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

## Метаданные

- **Канал:** Visually Explained
- **YouTube:** https://www.youtube.com/watch?v=f_CDxFEFj1k

## Содержание

### [0:00](https://www.youtube.com/watch?v=f_CDxFEFj1k) 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.

---
*Источник: https://ekstraktznaniy.ru/video/40232*