4 Python Scope

1. What is Scope?

Scope means where a variable can be used in a program.

In simple words:
👉 Scope tells Python where a variable is visible and usable

2. Types of Scope in Python

Python has four main scopes:

  1. Local Scope

  2. Enclosing Scope

  3. Global Scope

  4. Built-in Scope

We will understand them one by one in a simple way.

3. Local Scope

A local variable is created inside a function.

👉 It can be used only inside that function.

Example


 

❌ This will cause error:


 

4. Global Scope

A global variable is created outside all functions.

👉 It can be used anywhere in the program.

Example


 

5. Local and Global Variable with Same Name

Example


 

Output:


 

👉 Local variable does not change global variable.

6. The global Keyword

Use global when you want to change a global variable inside a function.

Example


 

7. Enclosing Scope (Function Inside Function)

This happens when a function is inside another function.

Example


 

8. Built-in Scope

Python has built-in variables and functions like:

  • print()

  • len()

  • sum()

Example


 

9. Common Beginner Mistakes

❌ Using Local Variable Outside Function


 

❌ Error.

❌ Forgetting global Keyword


 

❌ Error.

✔ Correct:


 

10. Simple Practice Examples

Example 1: Local Scope


 

Example 2: Global Scope


 

Example 3: Enclosing Scope


 

11. Summary (Python Scope)

✔ Scope defines where variable works
✔ Local → inside function
✔ Global → outside function
✔ Enclosing → nested functions
✔ Built-in → Python default

📘 Perfect for Beginner eBook

This chapter is ideal for:

  • Python beginner books

  • School & college students

  • Self-learners

If you want next, I can write:

  • Lambda Functions

  • Recursion

  • Modules

  • Exception Handling

Just tell me 😊

You may also like...