Preventing Pitfalls
00:00 In this course, you saw a bunch of examples that were, to be honest, not always ideal Python code. Hopefully they at least helped you to understand better how scopes work, but in this lesson, we’ll refactor this code by putting some good programming practices into work.
00:18 There are four good programming practices in the context of scopes to keep in mind: use local names rather than global names, write self-contained functions, try to use unique object names no matter what scope you are in, and avoid global name modifications throughout your programs.
00:39 To show you those four programming practices in code, let’s revisit the example from the last lesson.
00:48
On the left side, you see the code that you already know. You’re using the global
statement to increase the counter
global variable.
00:57 This code is not ideal, so on the right side, you see an updated version.
01:03
In the end, both versions will increase the global counter
variable, but on the right side, you write a self-contained function that relies on local names rather than a global name.
01:14
This implementation of update_counter()
defines current_counter
as a parameter and returns its value augmented by 1
unit every time the function is called. This way, the result of update_counter()
depends on the current_counter
you use as an input and not the global variable counter
. So again, thinking of the good programming practices, you are using local names, the function is self-contained—so that means all variables that are needed are passed in—and the variable names are unique, so you’re using current_counter
in the update_counter()
function instead of counter
. And finally, you are not changing a global variable from within the local scope of the function. When you keep these things in mind, you will generally write better Python code.
02:08 That’s everything I wanted to show you about scopes in this course. In the last lesson, I will give you a short summary and also additional resources to continue your Python journey.
Become a Member to join the conversation.