Python Programming
python function concepts like call by value , call by reference and recursion
Python Function Concepts: Call by Value, Call by Reference, Local & Global Variables, Recursion
Introduction
In the previous chapter, we learned:
- Function Basics
- Function Definition
- Function Call
- Return Statement
- Parameters
- Arguments
Now we will learn some important concepts that every Python programmer should understand:
- Call by Value
- Call by Reference
- Local Variables
- Global Variables
- Recursion
- Practice Exercises
Call by Value vs Call by Reference
This is one of the most commonly asked interview questions.
However, there is an important fact:
Python does not use pure Call by Value or pure Call by Reference.
Python uses:
Call by Object Reference
also called:
Call by Object Sharing
To understand this, first learn Call by Value and Call by Reference.
Call by Value
In Call by Value, a copy of the value is sent to the function.
Changes inside the function do NOT affect the original variable.
Example (Concept)
x = 10
Function receives:
copy of x
Original x remains unchanged.
Visual Representation
Original Variable
x = 10
Copy
↓
Function(y)
y = 10
Changes affect y only
Example
def modify(num):
num = 100
print("Inside Function:", num)
x = 10
modify(x)
print("Outside Function:", x)
Output:
Inside Function: 100
Outside Function: 10
The original variable remains unchanged.
Call by Reference
In Call by Reference, the actual memory address is passed.
Changes inside the function affect the original variable.
Concept Example
Original Object
↑
|
Function receives reference
Any modification affects the original object.
Example (Conceptual)
Original List
↑
Function receives reference
Function changes list
Original list also changes
Python's Actual Behavior
Python uses:
Call by Object Reference
The function receives a reference to the object.
Whether changes affect the original object depends on whether the object is mutable or immutable.
Immutable Objects
Immutable means:
Cannot be changed after creation
Examples:
- int
- float
- bool
- str
- tuple
Example with Integer
def modify(num):
num = 100
print(num)
x = 10
modify(x)
print(x)
Output:
100
10
Original value unchanged.
Example with String
def change(text):
text = "Python"
print(text)
name = "Java"
change(name)
print(name)
Output:
Python
Java
Strings are immutable.
Mutable Objects
Mutable means:
Can be modified after creation
Examples:
- list
- set
- dictionary
- bytearray
Example with List
def modify(data):
data.append(100)
numbers = [1, 2, 3]
modify(numbers)
print(numbers)
Output:
[1, 2, 3, 100]
Original list changed.
Why Did the List Change?
Because:
Both variable and parameter
refer to same object.
Visual:
numbers
↓
[1,2,3]
data
↓
[1,2,3]
Same object.
Preventing Original List Modification
Use copy().
def modify(data):
data.append(100)
numbers = [1, 2, 3]
modify(numbers.copy())
print(numbers)
Output:
[1, 2, 3]
Common Mistakes in Call by Reference
Mistake 1
Unexpected List Modification
def add_item(items):
items.append("Book")
Original list changes.
Solution
items.copy()
Mistake 2
Thinking Integers Behave Like Lists
def change(x):
x = 100
Original integer won't change.
Local Variables
What is a Local Variable?
A variable created inside a function is called a local variable.
It exists only while the function is executing.
Example
def test():
x = 100
print(x)
test()
Output:
100
Scope of Local Variable
def test():
x = 50
print(x)
test()
Output:
50
Outside the function:
print(x)
Output:
NameError
Visual Representation
Function Starts
|
V
Local Variable Created
|
V
Function Ends
|
V
Variable Destroyed
Global Variables
A variable defined outside a function is called a global variable.
Example
x = 100
def show():
print(x)
show()
Output:
100
Accessing Global Variables
country = "India"
def display():
print(country)
display()
Output:
India
Local Variable Hides Global Variable
x = 100
def test():
x = 50
print(x)
test()
print(x)
Output:
50
100
The local variable hides the global variable.
Modifying Global Variables
Problem
count = 0
def increase():
count = count + 1
Output:
UnboundLocalError
global Keyword
Use:
global variable_name
Example
count = 0
def increase():
global count
count += 1
increase()
print(count)
Output:
1
Multiple Calls
count = 0
def increase():
global count
count += 1
increase()
increase()
increase()
print(count)
Output:
3
Common Mistakes with Global Variables
Mistake 1
Modifying Global Variable Without global
score = 10
def update():
score += 1
Output:
UnboundLocalError
Correct
global score
Mistake 2
Overusing Global Variables
Bad:
name
age
salary
city
department
all global.
Better:
Pass values through parameters.
Local vs Global Variable
| Local Variable | Global Variable |
|---|---|
| Created inside function | Created outside function |
| Accessible only inside function | Accessible everywhere |
| Temporary | Exists until program ends |
| Safer | Can cause side effects |
Recursion
What is Recursion?
A function calling itself is called recursion.
Visual Representation
Function
|
Calls Itself
|
Calls Itself
|
Calls Itself
Basic Example
def hello():
print("Hello")
hello()
This creates an infinite recursion.
Output:
RecursionError
Base Case
Every recursive function must have a stopping condition.
This is called:
Base Case
Without it:
Infinite Recursion
Example
def countdown(n):
if n == 0:
return
print(n)
countdown(n - 1)
countdown(5)
Output:
5
4
3
2
1
How Recursion Works
countdown(3)
print(3)
countdown(2)
print(2)
countdown(1)
print(1)
countdown(0)
stop
Factorial Using Recursion
Formula:
5! = 5 × 4 × 3 × 2 × 1
Recursive Solution
def factorial(n):
if n == 1:
return 1
return n * factorial(n - 1)
print(factorial(5))
Output:
120
Recursion Tree
factorial(5)
5 × factorial(4)
5 × 4 × factorial(3)
5 × 4 × 3 × factorial(2)
5 × 4 × 3 × 2 × factorial(1)
5 × 4 × 3 × 2 × 1
Sum of Numbers Using Recursion
def total(n):
if n == 0:
return 0
return n + total(n - 1)
print(total(5))
Output:
15
Recursive Fibonacci
Sequence:
0 1 1 2 3 5 8 13 ...
def fibonacci(n):
if n <= 1:
return n
return fibonacci(n - 1) + fibonacci(n - 2)
print(fibonacci(6))
Output:
8
Common Recursion Mistakes
Mistake 1
Missing Base Case
def test():
test()
Output:
RecursionError
Mistake 2
Wrong Base Case
if n == 100:
when recursion never reaches 100.
Mistake 3
Not Moving Toward Base Case
factorial(n + 1)
instead of:
factorial(n - 1)
When to Use Recursion?
Good For:
- Factorial
- Tree Traversal
- Folder Structures
- Graph Algorithms
- Divide and Conquer Algorithms
Examples:
- Merge Sort
- Quick Sort
- Binary Search
Practice Exercises
Exercise 1
Create a function that doubles a number.
Solution
def double(number):
return number * 2
print(double(10))
Output:
20
Exercise 2
Create a function that returns the cube of a number.
Solution
def cube(number):
return number ** 3
print(cube(3))
Output:
27
Exercise 3
Create a global variable called company.
Print it inside a function.
Solution
company = "OpenAI"
def show():
print(company)
show()
Exercise 4
Create a counter using global variable.
Solution
counter = 0
def increase():
global counter
counter += 1
increase()
print(counter)
Exercise 5
Print numbers from 5 to 1 using recursion.
Solution
def countdown(n):
if n == 0:
return
print(n)
countdown(n - 1)
countdown(5)
Exercise 6
Find factorial of 6 using recursion.
Solution
def factorial(n):
if n == 1:
return 1
return n * factorial(n - 1)
print(factorial(6))
Output:
720
Exercise 7
Find sum from 1 to 10 using recursion.
Solution
def total(n):
if n == 0:
return 0
return n + total(n - 1)
print(total(10))
Output:
55
Quick Revision
| Topic | Description |
|---|---|
| Call by Value | Copy of value sent |
| Call by Reference | Reference sent |
| Python Mechanism | Call by Object Reference |
| Mutable Object | Can change |
| Immutable Object | Cannot change |
| Local Variable | Inside function |
| Global Variable | Outside function |
| global Keyword | Modify global variable |
| Recursion | Function calls itself |
| Base Case | Stopping condition |
Summary
| Concept | Key Point |
|---|---|
| Local Variable | Exists only inside function |
| Global Variable | Accessible throughout program |
| global | Used to modify global variables |
| Mutable Objects | Lists, sets, dictionaries |
| Immutable Objects | int, float, str, tuple |
| Recursion | Function calling itself |
| Base Case | Prevents infinite recursion |
| Recursive Call | Function calls itself again |
Before moving ahead, make sure you can confidently:
✅ Explain local and global variables
✅ Use the global keyword
✅ Explain mutable vs immutable objects
✅ Understand Python's call-by-object-reference behavior
✅ Write recursive functions
✅ Create factorial and sum programs using recursion