Technical Roadmap

Scope of a python variable

If you've ever tried to use a variable and got a NameError, you've already met Variable Scope. Scope of a variable is the area in your code from where you can call it. Outside that area, you can't call it.

  • L (Local): Variables you made inside the function you're currently in.
  • G (Global): Variables sitting at the very top of your file, outside everything.

Local vs. Global (The Public vs. Private)

💡 The Logicoria Tip

Think of a global variable like your Instagram DP—everyone can see it. But the posts inside a private account are Local; only those who you allow can see them.

  • Global Variable: Created in the main body of the script (outside all functions). Any function can use it.
  • Local Variable: Created inside a def function block. It is a private part of a specific function and is only accessible inside that function.
Python (Easy Scope)
# GLOBAL - Out in the open
name = "Logicoria"

def my_function():
# LOCAL - Hidden inside here
msg = "Hello"
print(msg)
print(name)

my_function()

This works (Global)
print(name)

This would CRASH (Local)
print(msg)
Output
Hello
Logicoria
Logicoria

Interview / Exam Tip

  • The global Keyword: This is a common exam question. If you want to change a global variable from inside a function, you have to use global var_name. If you don't, Python just creates a "copy" locally and ignores the global one.
  • Variable Shadowing: If you name a local variable the same as a global one, the local one "hides" the global one. It’s a classic way to cause bugs!