E-Books

🧩 Scope and Modules in Python

Scope refers to the area of your program where a variable is recognized.

A module is just a file that contains Python code β€” functions, variables, or classes β€” which you can reuse.

🧩 Local Scope in Python

A variable defined inside a function is local to that function.


  def my_func():
      x = 10  # βœ… Can access inside only
      print(x)

  my_func()  # βœ… Works
  print(x)   # ❌ Error: x is not defined outside
            

🧩 Global Scope in Python

A variable defined outside any function is accessible globally.


  x = 50

  def show():
      print(x)  # βœ… Can access inside global variable

  show()
  print(x)  # βœ… Can access outside global variable
            

🧩 The global Keyword in Python

Use global if you want to modify a global variable inside a function.


  x = 5

  def modify():
      global x # βœ… modify global variable x
      x = 10

  modify()
  print(x)  # Output: 10
            

🧩 The nonlocal Keyword in Python

nonlocal allows modifying variables (Inside Nested Functions) from the outer enclosing function, not the global one.


  def outer():
      x = "Python"
      def inner():
          nonlocal x
          x = "Scope"
      inner()
      print(x)

  outer()  # Output: Scope
            

🧩 Scope of Objects and Names in Python

In Python, when you create a variable (name), it is stored in a namespace, and its scope decides where it can be accessed.

Python uses the LEGB Rule to decide which variable to use:


  x = "Global"

  def outer():
      x = "Enclosing"

      def inner():
          x = "Local"
          print(x)  # πŸ” Prints Local

      inner()
      print(x)      # πŸ” Prints Enclosing

  outer()
  print(x)          # πŸ” Prints Global
            

🧩 LEGB Rule Order of Scope in Python

Scope Level Description Example Usage
⬇️ L – Local Inside a function (function’s own scope) Variable inside def my_func():
⬇️ E – Enclosing Inside outer functions (for nested functions) Nested def outer(): def inner():
⬇️ G – Global Top-level of the script or module Defined outside all functions
⬇️ B – Built-in Predefined by Python (like print, len, range) Comes from Python itself

🧩 L - Local scope in Python

Variables defined inside a function are local. They can only be accessed within that function.


  def show():
      x = 10  # Local variable βœ…
      print(x)     # Accessing local variable βœ…

  show()  # Output: 10 βœ…

  print(x)  # ❌ Error: 'x' is not defined outside the function
            

🧩 E - Enclosing scope in Python

Variables defined in an outer function, but not in the global scope. These variables are accessible to inner (nested) functions.


  def outer():
      x = 10  # Enclosing variable βœ…
              
      def inner():
          print(x)  # Accessing enclosing variable βœ…
              
      inner()  # Output: 10 βœ…
      print(x)  # Output: 10 βœ…

  outer()

  print(x)  # ❌ Error: 'x' is not defined outside the function
            

🧩 G - Global scope in Python

Variables defined at the top level of the script or module. They are accessible throughout the entire script, including inside functions (unless shadowed by local variables).


  x = 10  # Global variable βœ…

  def outer():
      def inner():
          print(x)  # Accessing global variable βœ…
      inner()  # Output: 10 βœ…
      print(x)  # Output: 10 βœ…

  outer()
  print(x)  # Output: 10 βœ…
            

🧩 B - Built-in scope in Python

Definition: The built-in scope contains all the standard Python functions and objects, like print(), len(), etc. These are always accessible in any Python script.


  def len(x):  # ❌ Overwriting built-in 'len' function
      return 0  # ❌ Always returns 0

  x = len('Python')  # ❌ Calls custom 'len', not built-in
  print(x)  # Output: 0
            

🧩 Python Modules

A module is just a Python file (.py) containing functions, classes, or variables.

Python has a large standard library, which includes many useful modules (like math, os, sys, etc.)


  # Import math Module
  import math

  # Return factorial of a number
  print(math.factorial(5))
            

🧩 Create a Module in Python

To create a module just save the Python code you want in a file with the file extension .py

Filename: my_module.py


  # my_module.py

  message = "Welcome to Python Modules!"  # Variable

  def greet(name):  # Function
      return f"Hello, {name}!"
            

🧩 Use a Module in Python

Filename: main.py


  # main.py

  import my_module  # Import the custom module

  print(my_module.message)  # Access variable βœ…
  print(my_module.greet("Deepak"))  # Call function βœ…
            

🧩 Types of Import in Python

Paragraph

Syntax Description Example
import modulename Imports the entire module. Use with prefix. import math
math.sqrt(16)
import module1, module2, module3 Imports multiple modules in a single line. import math, random, datetime
import module as aliasname Renames the module for easier reference. import numpy as np
import module1 as m1, module2 as m2 Renames multiple modules using aliases. import math as m, random as r
from module import member Imports a specific function/class/variable. from math import pi
from module import member1, member2, member3 Imports multiple specific members. from math import sqrt, floor, ceil
from module import member1 as aliasname Imports and renames a specific member. from math import sqrt as s
from module import * Imports all members β€” not recommended. from math import *
print(pi)
Previous Next