▶ Sign up free for the video, slides & prompts
The lesson below is open to all. Enter your email once to unlock every video, slide deck, prompt and code example on this device.
Checking…
Scope: local and global
Where a variable lives, and why globals cause bugs.
🎬 Video version coming soon — read it now
Scope is where a variable can be seen. It explains some confusing bugs, so it's worth five minutes.
Local variables stay inside
result is local: it exists only while the function runs. Each call gets fresh local variables, and they vanish when the function returns. To use the value outside, return it and store it.
Global variables are visible inside
A variable defined at the top level of your program is global. Functions can read it:
Writing constants in CAPITALS tells readers "this never changes".
Changing a global: the trap
Assigning to count inside the function makes Python treat it as a new local variable, which hasn't been given a value yet. You can fix it with the global keyword, but you usually shouldn't.
Pass in, return out
The clean way is to make the data flow visible:
Why globals cause bugs
When many functions change the same global variable, a wrong value could have come from any of them. With parameters and return values, you can see exactly where each value comes from.
The same names in different functions don't clash either:
Each r and pi is local to its own function.
In one line
Variables made inside a function are local; read globals only for constants, and pass values in and return them out.
Share with a friend