Technical Roadmap

Scope of a variable

If you've ever tried to use a variable and received a NameError, you've already encountered Variable Scope. The scope of a variable is the specific area in your code where that variable can be accessed or "called." Outside of that area, the variable simply doesn't exist to the program.

  • L (Local): Variables created inside the specific function you are currently in.
  • G (Global): Variables defined at the very top level of your script, outside of any functions.

Local vs. Global (Public vs. Private)

πŸ’‘ The Logicoria Tip

Think of a global variable like your Instagram DPβ€”everyone can see it. However, the posts inside a private account are Local; only those inside that specific "space" can access them.

  • Global Variable: Created in the main body of the script. Any function within that script can read and use it.
  • Local Variable: Created inside a def function block. it is "private" to that function and disappears once the function finishes running.
Python (Easy Scope)
# GLOBAL - Out in the open
name = "Logicoria"

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

my_function()

# This works (Global access)
print(name)

# This would CRASH (NameError: name 'msg' is not defined)
# print(msg)
Output:
Hello
Logicoria
Logicoria

Questions & Answers:

  • 1. What does the "scope" of a variable define?
    Scope defines the region of a program where a variable is recognized and can be accessed.
  • 2. Where is a global variable defined in a Python script?
    A global variable is defined in the main body of the script, outside of any function blocks.
  • 3. What happens if you try to print a local variable outside its function?
    Python will throw a NameError because the variable does not exist outside the function's scope.
  • 4. When should you use the global keyword inside a function?
    You use it when you want to change the value of a global variable from within the local scope of a function.
  • 5. What is "Variable Shadowing"?
    It occurs when a local variable has the same name as a global variable, causing the function to use the local value and ignore the global one.
  • 6. Which type of variable has a longer lifetime in memory: Local or Global?
    Global variables have a longer lifetime as they stay in memory for the entire duration of the program's execution.