Unit 1: Computational Thinking & Programming - 2
Chapter 1: Functions, Scope & Parameter Passing
1. Why Do We Need Functions?
A function is a named, reusable block of code that performs a specific task. Instead of writing the same logic again and again, we define it once and call it whenever needed.
Benefits: - Modularity: Breaks a large program into smaller, manageable pieces. - Reusability: Write once, use many times (DRY - Don't Repeat Yourself). - Easier Debugging: Errors can be isolated to a specific function.
Types of Functions in Python
- Built-in Functions: Provided by Python itself (e.g.,
print(),len(),int(),range()). - Library/Module Functions: Available after importing a module (e.g.,
math.sqrt(),random.randint()). - User-Defined Functions (UDF): Created by the programmer using the
defkeyword.
2. Defining and Calling a Function
def greet(name): # function header - 'name' is a parameter
message = "Hello, " + name + "!"
return message # sends a value back to the caller
print(greet("Riya")) # function call - "Riya" is an argument
- Parameter: The variable listed inside the parentheses in the function definition (
name). - Argument: The actual value passed during the function call (
"Riya"). - A function without an explicit
returnstatement returnsNoneby default. returnimmediately exits the function - any code written after it inside the function does not execute.
3. Types of Arguments
(a) Positional Arguments
Values are matched to parameters strictly by their order/position.
def power(base, exponent):
return base ** exponent
print(power(2, 3)) # 8 -> base=2, exponent=3
print(power(3, 2)) # 9 -> base=3, exponent=2 (order matters!)
(b) Default Arguments
A parameter can be given a default value, used only if the caller doesn't supply one. Rule: once a parameter has a default value, every parameter after it must also have one.
def power(base, exponent=2): # exponent defaults to 2
return base ** exponent
print(power(5)) # 25 -> uses default exponent=2
print(power(5, 3)) # 125 -> overrides the default
# INVALID - non-default argument 'y' cannot follow a default argument 'x'
def wrong(x=5, y):
return x + y
# SyntaxError: non-default argument follows default argument
(c) Keyword Arguments
Values are passed using the parameter=value syntax, so order no longer matters.
def student_info(name, cls, section):
print(name, cls, section)
student_info(cls=12, section="A", name="Aman") # order doesn't matter
A positional argument can never appear after a keyword argument in the same call.
4. Scope of Variables
Scope determines the region of a program where a variable is accessible.
| Scope | Where it is defined | Accessible from |
|---|---|---|
| Local | Inside a function | Only inside that function |
| Global | Outside all functions (at module level) | Anywhere in the program, including inside functions (read-only, by default) |
x = 10 # global variable
def show():
y = 5 # local variable - exists only inside show()
print(x, y) # can READ the global x
show()
print(x) # 10
print(y) # NameError: y is not defined (out of scope here)
Modifying a Global Variable Inside a Function
By default, assigning a value to a variable inside a function creates a new local variable, even if a global variable of the same name exists. To modify the actual global variable, use the global keyword.
count = 0
def increment_wrong():
count = count + 1 # UnboundLocalError - treated as local before assignment
def increment_correct():
global count
count = count + 1 # now modifies the global 'count'
increment_correct()
increment_correct()
print(count) # 2
5. Recursive vs Iterative Functions
A recursive function is a function that calls itself to solve a smaller instance of the same problem, until it reaches a base case that stops the recursion.
# Iterative factorial
def fact_iterative(n):
result = 1
for i in range(1, n + 1):
result *= i
return result
# Recursive factorial
def fact_recursive(n):
if n == 0 or n == 1: # base case
return 1
return n * fact_recursive(n - 1) # recursive call
print(fact_iterative(5)) # 120
print(fact_recursive(5)) # 120
| Iterative | Recursive |
|---|---|
Uses a loop (for/while) |
Function calls itself |
| Generally faster, uses less memory | Elegant for naturally recursive problems (factorial, Fibonacci, tree traversal) but uses more memory (call stack) |
| No risk of "maximum recursion depth" error | Must always have a base case, or it runs forever and crashes |
6. Board Exam Focus Questions
Q1. Find the output:
def calculate(a, b=10, c=20):
return a + b - c
print(calculate(5))
print(calculate(5, c=5))
Answer:
- calculate(5) → a=5, b=10 (default), c=20 (default) → 5 + 10 - 20 = -5
- calculate(5, c=5) → a=5, b=10 (default), c=5 (keyword) → 5 + 10 - 5 = 10
Q2. Rewrite the following code after removing errors, underlining each correction:
def Add(a, b = 5, c):
Result = a + b + c
Return result
Answer:
def Add(a, c, b=5): # default argument 'b' moved after non-default 'c'
Result = a + b + c
return Result # 'return' is lowercase; variable name must match case exactly
Q3. What will be the output of the following code?
def modify(lst):
lst.append(100)
numbers = [1, 2, 3]
modify(numbers)
print(numbers)
Answer: [1, 2, 3, 100] - Lists are mutable objects passed by reference, so changes made to the parameter inside the function reflect in the original object, unlike immutable types (int, string, tuple) which are effectively passed by value.