Skip to content
IT Vizag
← Functions & Clean Code

▶ 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

Lesson 4 of 9 · 2 min read

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

🔒 Code example: sign up free (above) to unlock it.

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:

🔒 Code example: sign up free (above) to unlock it.

Writing constants in CAPITALS tells readers "this never changes".

Changing a global: the trap

🔒 Code example: sign up free (above) to unlock it.

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:

🔒 Code example: sign up free (above) to unlock it.

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:

🔒 Code example: sign up free (above) to unlock it.

Each r and pi is local to its own function.

Tip: In Colab, variables from earlier cells are global and stick around. If code works for you but fails after Restart and run all, a forgotten global is often the cause.

In one line

Variables made inside a function are local; read globals only for constants, and pass values in and return them out.

Saved on this device. Sign in to keep progress everywhere.

Share with a friend