CodingNic

Functions and Reusability

Scope

Functions and Reusability 22 min read

Scope

Scope

Variables do not always work everywhere in a program.

Some variables only work inside a function.

Some variables can be used in many places.

This idea is called scope.

What Is Scope?

Scope means where a variable can be used.

Think of scope as the area where a variable is visible and available.

Two Main Types of Scope

  • Local scope
  • Global scope

Local Scope

A local variable is created inside a function.

It can only be used inside that function.

python
def greet():
    name = "Sara"
    print(name)

greet()

Output

text
Sara

The variable name works inside the function.

Outside the Function

python
def greet():
    name = "Sara"

greet()
print(name)

This gives an error because name only exists inside the function.

Global Scope

A global variable is created outside a function.

It can be used in many places.

python
city = "Toronto"

def show_city():
    print(city)

show_city()
print(city)

Output

text
Toronto
Toronto

The variable city is outside the function, so it is global.

Local and Global Together

If a local variable has the same name, Python uses the local one inside the function.

python
name = "John"

def show_name():
    name = "Maya"
    print(name)

show_name()
print(name)

Output

text
Maya
John

Why Scope Matters

Scope helps avoid confusion.

It keeps variables organized and prevents accidental changes.

Code Along

python
country = "Canada"

def show_country():
    print(country)

show_country()

Output

text
Canada

Mini Challenge

Build a scope checker.

Steps:

  • Create a global variable called color with value Blue
  • Create a function that prints color
  • Call the function
  • Print color again outside the function

Expected output:

text
Blue
Blue

Real World Use Case

Programs use scope to manage data in functions, apps, games, and large systems with many variables.

Quiz

  1. What does scope mean?
  2. Where does a local variable work?
  3. Where is a global variable created?
  4. Which variable is used first inside a function if names match?

Assignment

Create a global variable called language. Print it inside a function and outside the function.

Summary

You learned that scope controls where variables can be used, and the difference between local and global variables.