Explain the local and global scope with suitable examples. With an example explain user-defined functions.

Local and Global Scope in Python

Scope refers to the area of a program where a variable is recognized or accessible. Python uses two main types of scope:

🔹 Global Scope:

  • A variable declared outside all functions.
  • Accessible throughout the program, including inside functions (unless overridden).

🔹 Local Scope:

  • A variable declared inside a function.
  • Only accessible within that specific function.

Example for Global and Local Scope:

name = "Ram"  # Global variable

def greet():
    age = 20  # Local variable
    print("Hello", name)  # Can access global variable
    print("You are", age, "years old")

greet()

print("Name outside function:", name)  # Works

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

Explanation:

  • name is a global variable, accessible inside and outside the function.
  • age is a local variable, defined inside the greet() function, and cannot be accessed globally.

User-Defined Functions in Python

A user-defined function is a block of reusable code that performs a specific task and is created using the def keyword.

🔹 Syntax:

def function_name(parameters):
    return result

Example of a User-Defined Function:

def greet_user():
    name = input("What is your name? ")
    print("Hello, " + name + "! It is good to meet you.")

greet_user()

Explanation:

  • greet_user() is a user-defined function.
  • It uses the built-in input() function to take user input and the print() function to display a greeting message.
  • The variable name here is local to the greet_user() function.

Other Built-in Functions Used Inside User-Defined Functions:

FunctionPurpose
input()Accepts user input as a string
print()Displays output to the screen
len()Returns the length of a string
str(), int(), float()Converts between data types
type()Returns the type of a value
round(), abs()Mathematical operations

Understanding the concept of local and global scope helps avoid variable conflicts and unexpected errors. User-defined functions enhance modularity, code reusability, and make programs easier to read and maintain.

Leave a Reply

Your email address will not be published. Required fields are marked *