What is Computer

Module: M2-R5: Web Design & Publishing

Chapter: Ch1 Computer Intro

🔹 What are Local Variables?

A local variable is a variable that is declared and used inside a function. It exists only within that function’s scope and is destroyed once the function finishes execution.

Syntax:

def function_name():
    variable_name = value   # Local variable
    print(variable_name)
✅ Example of Local Variable
def greet():
    message = "Welcome to QuiteXams!"  # Local variable
    print(message)

greet()

# Trying to access it outside the function
print(message)  # This will cause an error

Output:

Welcome to QuiteXams!
NameError: name 'message' is not defined

➡ The variable message is local to the function greet() and cannot be accessed outside.

🔹 Characteristics of Local Variables
  • Declared inside a function.
  • Accessible only within that function.
  • Created when the function starts and destroyed when it ends.
  • Have local scope — not known outside the function.
🔹 Example: Local vs Global Variable
x = 10   # Global variable

def show():
    x = 5    # Local variable
    print("Inside function:", x)

show()
print("Outside function:", x)

Output:

Inside function: 5
Outside function: 10

➡ Here, x inside the function is local and different from the global x.

🔹 Local Variables with Parameters

Function parameters also behave as local variables within the function.

def add(a, b):
    sum = a + b     # sum, a, b are local variables
    print("Sum:", sum)

add(4, 6)
print(a)  # Error

Output:

Sum: 10
NameError: name 'a' is not defined

➡ Both a and b are local to add().

🔹 Lifetime of a Local Variable

The lifetime of a local variable begins when the function is called and ends when the function execution is completed.

def demo():
    x = 1
    x += 1
    print("x =", x)

demo()
demo()

Output:

x = 2
x = 2

➡ Each time the function runs, a new local copy of x is created.

✅ Summary
Feature Description
Declared Inside Function Yes
Accessible Outside Function No
Lifetime Created when function starts, destroyed when it ends
Example def func(): x = 5
💡 Key Points
  • Local variables exist only inside functions.
  • They are recreated every time the function runs.
  • They can have the same name as global variables (they don’t affect them).
Quick Links