Chapter 07: Functions
7.1 Introduction
As programs grow larger, they naturally become longer and more complex. If all instructions are written in one continuous block, several problems arise:
- The program becomes hard to read
- Errors become hard to locate
- The same logic may need to be written repeatedly
- Modifying one part risks breaking another part
To manage this complexity, programming languages provide a way to divide a large program into smaller, manageable parts.
These parts are called functions.
A function is a named block of code that performs a specific task and can be executed whenever required.
Why Functions Are Necessary (Conceptual Motivation)
Think of a function as a machine:
- You give it input
- It performs a defined operation
- It may give back a result
Instead of rewriting the same logic again and again, we:
- write it once
- give it a name
- reuse it wherever needed
This leads to:
- Code reuse
- Modularity
- Clarity
- Easier debugging
7.2 Functions
What Exactly Is a Function?
In Python, a function is:
- a group of related statements
- given a name
- executed only when it is called
A function may:
- accept data (parameters)
- return a value
- or simply perform an action
Basic Idea with an Example
Without function:
a = 10
b = 20
print(a + b)
x = 5
y = 7
print(x + y)
Problem:
- Same logic repeated
- Difficult to scale
With function:
def add(p, q):
print(p + q)
add(10, 20)
add(5, 7)
Now:
- Logic is written once
- Reused multiple times
Types of Functions in Python (NCERT Classification)
Python supports two broad categories:
- Built-in functions
- User-defined functions
7.3 User Defined Functions
Why User-Defined Functions Exist
Built-in functions handle common tasks. But programs often require custom operations specific to a problem.
User-defined functions allow programmers to:
- define their own operations
- structure programs logically
- reduce duplication
Defining a Function
A function is defined using the keyword def.
General Syntax
def function_name(parameters):
statement(s)
Important points:
deftells Python a function is being defined- Function name follows identifier rules
- Parentheses may contain parameters
- Indentation defines the function body
Example: Simple Function
def greet():
print("Welcome to Python")
At this point:
- Python knows the function
- But it does not execute it
Calling a Function
A function executes only when called.
greet()
Execution flow:
- Python encounters function call
- Control jumps to function definition
- Statements inside function execute
- Control returns to caller
Functions with Parameters
Parameters allow data to be passed into a function.
def square(n):
print(n * n)
square(5)
square(10)
Here:
nis a parameter5and10are arguments
Functions with Return Value
So far, functions only displayed output. Often, we want functions to send results back.
This is done using return.
def square(n):
return n * n
result = square(6)
print(result)
Key concept:
returnsends value back to caller- Function execution stops at
return
Function Without Return
def display(msg):
print(msg)
Such functions return None implicitly.
Multiple Parameters
def add(a, b):
return a + b
print(add(3, 4))
Why Functions Improve Debugging
When errors occur:
- You know which function failed
- You can test functions individually
- Fixing one function does not affect others
This modularity is a core reason functions exist.
7.4 Scope of a Variable
Why Variable Scope Matters
Variables do not exist everywhere in a program. If they did, programs would:
- overwrite values unintentionally
- become unpredictable
Scope defines where a variable can be accessed.
Python mainly deals with:
- Local variables
- Global variables
Local Variables
Variables defined inside a function are local.
def test():
x = 10
print(x)
test()
Here:
xexists only insidetest()Outside access causes error
print(x) # NameError
Why?
- Once function execution ends, local variables are destroyed
Global Variables
Variables defined outside all functions are global.
x = 20
def show():
print(x)
show()
Here:
xis accessible inside function- Python first looks in local scope
- Then in global scope
Local vs Global (Key Difference)
| Local | Global | | - | - | | Defined inside function | Defined outside function | | Exists only during function execution | Exists throughout program | | Safer | Risky if modified |
Modifying Global Variables Inside Functions
By default, functions cannot modify global variables.
x = 10
def change():
x = 20 # creates local variable
change()
print(x)
Output:
10
To modify global variable, global keyword is required.
x = 10
def change():
global x
x = 20
change()
print(x)
Now output is:
20
NCERT emphasizes:
π Avoid unnecessary use of global β it makes programs harder to debug.
7.5 Python Standard Library
What Is a Library?
A library is a collection of pre-written functions and modules that perform common tasks.
Python comes with a rich standard library, so programmers donβt have to write everything from scratch.
Why the Standard Library Is Important
- Saves time
- Reduces errors
- Provides tested and optimized code
- Makes Python powerful despite simple syntax
Using Library Modules
To use a module, we must import it.
import math
Example: math Module
import math
print(math.sqrt(16))
print(math.factorial(5))
print(math.pi)
Explanation:
math.sqrt()calculates square rootmath.factorial()calculates factorialmath.pigives value of Ο
Selective Import
from math import sqrt, pi
print(sqrt(25))
print(pi)
Commonly Used Standard Library Modules (NCERT)
mathβ mathematical operationsrandomβ random number generationstatisticsβ mean, median, modetimeβ time-related functions
Example: random Module
import random
print(random.randint(1, 6))
Used in:
- games
- simulations
- sampling
Key Conceptual Takeaways
- In programming, functions are used to achieve modularity and reusability.
- Function can be defined as a named group of instructions that are executed when the function is invoked or called by its name. Programmers can write their own functions known as
user defined functions. - The Python interpreter has a number of functions built into it. These are the functions that are frequently used in a Python program. Such functions are known as
built-in functions. - An
argumentis a value passed to the function during function call which is received in aparameterdefined in function header. - Python allows assigning a
default valueto the parameter. - A function returns value(s) to the calling function using
returnstatement. - Multiple values in Python are returned through a
Tuple. - Flow of execution can be defined as the order in which the statements in a program are executed.
- The part of the program where a variable is accessible is defined as the
scopeof the variable. - A variable that is defined outside any particular function or block is known as a
global variable. It can be accessed anywhere in the program. - A variable that is defined inside any function or block is known as a
local variable. It can be accessed only in the function or block where it is defined. It exists only till the function executes or remains active. - The Python
standard libraryis an extensive collection of functions and modules that help the programmer in the faster development of programs. - A
moduleis a Python file that contains definitions of multiple functions. - A module can be imported in a program using
importstatement. - Irrespective of the number of times a module is imported, it is loaded only once.
- To import specific functions in a program from a module,
fromstatement can be used.