CBSE Class 11 Computer Science Chapter 7 — Functions
Functions are one of the most important building blocks in Python programming. They allow you to organise your code into reusable, logical units — making programs easier to read, write, and debug. This chapter covers everything you need for your CBSE Class 11 exams: from defining and calling functions to understanding scope, recursion, and modules.
Chapter Introduction
Imagine you are writing a program that calculates the average of marks in five different subjects for ten different students. Without functions, you would have to write the same calculation code ten times. With functions, you write it once and call it ten times. That is the power of functions — reusability.
A function is a self-contained block of code that performs a specific task. Python gives you built-in functions like print(), len(), and input(), and also lets you create your own user-defined functions.
This chapter aligns with NCERT Chapter 7 and covers all concepts tested in CBSE board and school examinations.
Key Definitions
| Term | Definition |
|---|---|
| Function | A named, reusable block of code that performs a specific task |
| Parameter | A variable listed in the function definition that receives a value |
| Argument | The actual value passed to a function when it is called |
| Return value | The value a function sends back to the caller using the return statement |
| Local variable | A variable defined inside a function; accessible only within that function |
| Global variable | A variable defined outside all functions; accessible throughout the program |
| Default argument | A parameter that takes a pre-set value if no argument is supplied |
| Keyword argument | An argument passed by explicitly naming the parameter |
| Recursion | A technique where a function calls itself to solve a problem |
| Module | A file containing Python definitions and statements that can be imported |
| Docstring | A string literal placed right after the function header to document what the function does |
Detailed Concepts
1. What is a Function?
A function is a named block of reusable code that performs a specific task. Instead of writing the same code repeatedly, you define a function once and call it whenever needed.
Advantages of using functions:
1. Reusability — Write once, use many times. No need to duplicate code. 2. Readability — A well-named function makes code self-explanatory. calculate_average() is clearer than a block of arithmetic. 3. Modularity — Complex programs are broken into smaller, manageable pieces. 4. Easier debugging — Isolate and fix bugs in one function without disturbing the rest of the program. 5. Reduced complexity — Each function handles one task, keeping logic simple.
Example without a function:
# Calculating area for three circles — repetitive code
r1 = 5
area1 = 3.14159 * r1 * r1
print("Area:", area1)
r2 = 7
area2 = 3.14159 * r2 * r2
print("Area:", area2)
r3 = 10
area3 = 3.14159 * r3 * r3
print("Area:", area3)
Example with a function:
def circle_area(radius):
"""Calculate the area of a circle."""
return 3.14159 * radius * radius
print("Area:", circle_area(5))
print("Area:", circle_area(7))
print("Area:", circle_area(10))
The function version is shorter, cleaner, and if you later want to use a more precise value of pi, you change it in only one place.
2. Defining a Function
You define a function using the def keyword, followed by the function name, parentheses for parameters, and a colon. The function body is indented.
Syntax:
def function_name(parameters):
"""Docstring — describes what the function does."""
# function body
return value # optional
Example:
def greet(name):
"""Greet a person by name."""
message = "Hello, " + name + "!"
return message
Key points:
- The function name should be descriptive and follow snake_case convention (e.g.,
calculate_total). - The docstring is optional but highly recommended. It is the first string inside the function and can be accessed using
function_name.__doc__. - The
returnstatement is optional. If omitted, the function returnsNone.
def say_hello():
"""Print a greeting."""
print("Hello, World!")
# The function returns None because there is no return statement
result = say_hello()
print(result) # Output: None
3. Calling a Function
After defining a function, you call it by writing its name followed by parentheses and any required arguments.
Syntax:
function_name(arguments)
Examples:
# Function with no arguments
def welcome():
print("Welcome to KalviGavani!")
welcome() # Output: Welcome to KalviGavani!
# Function with one argument
def greet(name):
print("Hello,", name)
greet("Arjun") # Output: Hello, Arjun
# Function with multiple arguments
def add(a, b):
return a + b
result = add(3, 5)
print(result) # Output: 8
You can also assign the return value of a function to a variable, use it in expressions, or pass it as an argument to another function.
def square(n):
return n * n
def sum_of_squares(x, y):
return square(x) + square(y)
print(sum_of_squares(3, 4)) # Output: 25
4. Parameters and Arguments
Parameters are variables in the function definition. Arguments are the actual values passed when calling the function.
4.1 Positional Arguments
Arguments are matched to parameters based on their position (order).
def student_info(name, age, city):
print(name, "is", age, "years old and lives in", city)
student_info("Priya", 16, "Chennai")
# name = "Priya", age = 16, city = "Chennai"
The order matters. student_info("Chennai", 16, "Priya") would assign the wrong values.
4.2 Default Arguments
Parameters can have default values. If the caller does not provide an argument, the default is used.
def greet(name, msg="Good morning"):
print(msg + ",", name)
greet("Ravi") # Output: Good morning, Ravi
greet("Ravi", "Hi") # Output: Hi, Ravi
Rule: Non-default parameters cannot follow default parameters.
# WRONG — syntax error
def greet(msg="Good morning", name):
print(msg + ",", name)
# CORRECT — default parameters come last
def greet(name, msg="Good morning"):
print(msg + ",", name)
4.3 Keyword Arguments
Arguments passed by explicitly naming the parameter. Order does not matter.
def student_info(name, age, city):
print(name, "is", age, "years old and lives in", city)
student_info(city="Delhi", name="Amit", age=17)
# Output: Amit is 17 years old and lives in Delhi
4.4 Variable-Length Arguments
When you do not know how many arguments will be passed, use args (for positional) and *kwargs (for keyword).
*args — collects extra positional arguments into a tuple:**
def total(*numbers):
return sum(numbers)
print(total(1, 2, 3)) # Output: 6
print(total(10, 20, 30, 40)) # Output: 100
kwargs — collects extra keyword arguments into a dictionary:**
def display_info(**details):
for key, value in details.items():
print(key, ":", value)
display_info(name="Kavya", age=16, city="Bengaluru")
# Output:
# name : Kavya
# age : 16
# city : Bengaluru
5. Return Statement
The return statement sends a value back to the caller and exits the function immediately.
Returning a single value:
def square(n):
return n * n
result = square(5)
print(result) # Output: 25
Returning multiple values (as a tuple):
def calc(a, b):
return a + b, a - b, a * b
s, d, p = calc(10, 3)
print("Sum:", s, "Difference:", d, "Product:", p)
# Output: Sum: 13 Difference: 7 Product: 30
No return statement — function returns None:
def greet(name):
print("Hello,", name)
result = greet("Sam")
print(result) # Output: None
Return exits immediately:
def check_even(n):
if n % 2 == 0:
return True
return False
print(check_even(4)) # Output: True
print(check_even(7)) # Output: False
6. Scope of Variables
Scope determines where a variable can be accessed in a program.
6.1 Local Variables
A variable created inside a function is local to that function. It cannot be accessed from outside.
def my_function():
x = 10 # local variable
print("Inside function:", x)
my_function()
# print(x) # ERROR — x is not defined outside the function
6.2 Global Variables
A variable created outside all functions is global. It can be accessed anywhere in the program.
school = "KalviGavani" # global variable
def display():
print("School:", school) # can access global variable
display() # Output: School: KalviGavani
6.3 The global Keyword
To modify a global variable inside a function, you must use the global keyword.
counter = 0 # global variable
def increment():
global counter
counter += 1
increment()
print(counter) # Output: 1
Without global, Python treats counter inside the function as a new local variable.
counter = 0
def increment():
counter = 10 # this is a NEW local variable
print("Local:", counter)
increment() # Output: Local: 10
print("Global:", counter) # Output: Global: 0
6.4 The LEGB Rule
Python resolves variable names using the LEGB lookup order:
1. Local — inside the current function 2. Enclosing — in enclosing function scopes (for nested functions) 3. Global — at the module (file) level 4. Built-in — Python's built-in names like len, print, int
x = "global"
def outer():
x = "enclosing"
def inner():
x = "local"
print(x) # Output: local
inner()
outer()
6.5 The globals() Function
The globals() function returns a dictionary of all global variables.
name = "KalviGavani"
def show_globals():
print(globals()["name"])
show_globals() # Output: KalviGavani
7. Default Arguments — Deep Dive
Default arguments let you define functions that can be called with fewer arguments than they are defined to accept.
Example — calculating simple interest:
def simple_interest(principal, rate=5, time=1):
"""Calculate simple interest. Rate defaults to 5%, time defaults to 1 year."""
return (principal * rate * time) / 100
print(simple_interest(1000)) # Output: 50.0
print(simple_interest(1000, 8)) # Output: 80.0
print(simple_interest(1000, 8, 2)) # Output: 160.0
print(simple_interest(1000, time=3)) # Output: 150.0
Rules for default arguments:
1. Non-default parameters must come before default parameters. 2. Default values are evaluated only once at function definition time (be careful with mutable defaults). 3. You can mix positional and keyword arguments when calling.
Pitfall — mutable default arguments:
# WRONG — the same list is shared across calls
def append_item(item, my_list=[]):
my_list.append(item)
return my_list
print(append_item(1)) # Output: [1]
print(append_item(2)) # Output: [1, 2] — unexpected!
# CORRECT — use None as default
def append_item(item, my_list=None):
if my_list is None:
my_list = []
my_list.append(item)
return my_list
print(append_item(1)) # Output: [1]
print(append_item(2)) # Output: [2] — correct
8. Keyword Arguments — Deep Dive
Keyword arguments make function calls more readable and allow you to skip optional parameters.
def create_profile(name, age, city="Not specified", hobby="Not specified"):
print("Name :", name)
print("Age :", age)
print("City :", city)
print("Hobby:", hobby)
create_profile(name="Ananya", age=17, hobby="Painting")
# Output:
# Name : Ananya
# Age : 17
# City : Not specified
# Hobby: Painting
You can mix positional and keyword arguments, but positional arguments must come first:
# CORRECT
create_profile("Ananya", 17, hobby="Painting")
# WRONG — keyword argument before positional
# create_profile(name="Ananya", 17) # SyntaxError
9. Recursion
Recursion is a technique where a function calls itself to solve a problem by breaking it into smaller sub-problems.
Every recursive function needs: 1. Base case — the condition that stops recursion. 2. Recursive case — the function calls itself with a smaller input.
Example — factorial of a number:
def factorial(n):
"""Calculate the factorial of n using recursion."""
if n == 0 or n == 1: # base case
return 1
else: # recursive case
return n * factorial(n - 1)
print(factorial(5)) # Output: 120
How it works:
factorial(5)returns5 * factorial(4)factorial(4)returns4 * factorial(3)factorial(3)returns3 * factorial(2)factorial(2)returns2 * factorial(1)factorial(1)returns1(base case)- Values unwind:
1 → 2 → 6 → 24 → 120
Example — Fibonacci sequence:
def fibonacci(n):
"""Return the nth Fibonacci number."""
if n <= 0:
return 0
elif n == 1:
return 1
else:
return fibonacci(n - 1) + fibonacci(n - 2)
print(fibonacci(6)) # Output: 8
Caution — stack overflow:
If the base case is missing or never reached, recursion continues indefinitely, causing a RecursionError.
def infinite_recursion(n):
return n * infinite_recursion(n - 1) # no base case!
# infinite_recursion(5) # RecursionError: maximum recursion depth exceeded
Python has a default recursion limit of 1000. You can check it with:
import sys
print(sys.getrecursionlimit()) # Output: 1000
10. Modules
A module is a file containing Python code (functions, classes, variables) that can be imported into other programs.
10.1 Importing a Module
Import the entire module:
import math
print(math.sqrt(16)) # Output: 4.0
print(math.pi) # Output: 3.141592653589793
Import specific names:
from math import sqrt, pi
print(sqrt(25)) # Output: 5.0
print(pi) # Output: 3.141592653589793
Import with alias:
import math as m
print(m.factorial(5)) # Output: 120
Import all names (not recommended for large modules):
from math import *
print(sqrt(36)) # Output: 6.0
10.2 Creating Your Own Module
Save the following code in a file named mymodule.py:
# mymodule.py
def add(a, b):
return a + b
def subtract(a, b):
return a - b
greeting = "Hello from mymodule!"
Then import and use it in another file:
import mymodule
print(mymodule.add(5, 3)) # Output: 8
print(mymodule.greeting) # Output: Hello from mymodule!
10.3 The math Module
import math
print(math.ceil(4.3)) # Output: 5
print(math.floor(4.7)) # Output: 4
print(math.fabs(-5)) # Output: 5.0
print(math.pow(2, 3)) # Output: 8.0
print(math.log10(100)) # Output: 2.0
print(math.gcd(12, 18)) # Output: 6
10.4 The random Module
import random
print(random.random()) # Output: random float between 0.0 and 1.0
print(random.randint(1, 10)) # Output: random integer between 1 and 10
print(random.choice([1, 2, 3, 4])) # Output: random element from the list
10.5 Using dir()
The dir() function returns a list of all attributes and methods in a module.
import math
print(dir(math))
# Output: ['__doc__', '__name__', ..., 'ceil', 'floor', 'pi', 'sqrt', ...]
11. Standard Library Functions
Python provides many built-in functions that are always available without importing.
| Function | Description | Example |
|---|---|---|
len() | Returns the length | len("Python") → 6 |
type() | Returns the data type | type(5) → <class 'int'> |
input() | Reads user input | input("Enter name: ") |
int() | Converts to integer | int("5") → 5 |
float() | Converts to float | float("3.14") → 3.14 |
str() | Converts to string | str(10) → "10" |
abs() | Returns absolute value | abs(-7) → 7 |
round() | Rounds a number | round(3.7) → 4 |
min() | Returns minimum | min(3, 1, 7) → 1 |
max() | Returns maximum | max(3, 1, 7) → 7 |
sum() | Returns sum | sum([1, 2, 3]) → 6 |
sorted() | Returns sorted list | sorted([3, 1, 2]) → [1, 2, 3] |
pow() | Returns x raised to y | pow(2, 3) → 8 |
id() | Returns object identity | id(5) → memory address |
12. Parameters vs Arguments — Comparison
| Aspect | Parameters | Arguments |
|---|---|---|
| What | Variables in the function definition | Actual values passed during the call |
| Where | Appear in the function header | Appear in the function call |
| Also called | Formal parameters | Actual parameters |
| Example | def add(a, b): — a, b are parameters | add(3, 5) — 3, 5 are arguments |
| Memory | Allocated when function is called | Values already exist before the call |
def multiply(x, y): # x, y are PARAMETERS
return x * y
result = multiply(4, 6) # 4, 6 are ARGUMENTS
Common Mistakes
1. Forgetting the colon after the function header — def greet(name) instead of def greet(name):.
2. Incorrect indentation — The function body must be indented consistently. Mixing tabs and spaces causes errors.
3. Using a variable before calling the function — Local variables do not exist until the function runs.
4. Modifying a global variable without the global keyword — Python creates a new local variable instead of modifying the global one.
5. Placing default parameters before non-default parameters — def f(a=1, b): causes a SyntaxError. Default parameters must come last.
6. Using mutable objects as default arguments — Lists and dictionaries as defaults are shared across all calls, leading to unexpected behaviour.
7. Missing base case in recursion — This causes infinite recursion and a RecursionError.
8. Confusing parameters and arguments — Parameters are in the definition; arguments are in the call.
9. Not returning a value — If you forget return, the function returns None. This is especially easy to miss when the function should return a calculation result.
10. Calling a function before it is defined — Python reads code top-to-bottom. A function must be defined before it is called.
Exam Tips
1. Always write the def keyword and colon when defining a function. Examiners check for correct syntax first.
2. Include docstrings in your function definitions. They earn you marks and show good programming practice.
3. Trace through recursive calls step by step in the exam. Write out each call: factorial(3) → 3 factorial(2) → 3 2 factorial(1) → 3 2 * 1 → 6.
4. Draw scope diagrams when asked about local vs global variables. Clearly mark which variables belong to which scope.
5. For output-based questions, manually trace the code line by line. Write variable values after each line.
6. Remember: return exits the function immediately. Any code after return is not executed.
7. When asked to "write a function", always include: function definition, docstring, body, and at least one sample call with expected output.
8. Know the difference between print and return — print displays a value; return sends a value back to the caller. Examiners frequently test this distinction.
9. For module questions, remember to include the import statement. Using math.sqrt() without import math will cause a NameError.
10. Practise writing functions with default and keyword arguments — these are commonly tested in 2-mark and 3-mark questions.
Quick Revision Notes
- A function is defined with
def, called by its name with parentheses. - Parameters are in the definition; arguments are in the call.
returnsends a value back and exits the function. Noreturnmeans the function returnsNone.- Local variables exist only inside the function. Global variables exist everywhere.
- Use the
globalkeyword to modify a global variable inside a function. - LEGB rule: Local → Enclosing → Global → Built-in.
- Default arguments must come after non-default arguments.
- Keyword arguments are passed by name; order does not matter.
*argscollects extra positional arguments into a tuple.**kwargscollects extra keyword arguments into a dictionary.- Recursion needs a base case (stop condition) and a recursive case.
- Modules are imported with
import,from...import, orimport...as. dir(module)lists all names in a module.- Common modules:
math(mathematical functions),random(random numbers). - Mutable default arguments (like lists) are a common pitfall — use
Noneinstead.
For complete exercise solutions, see [Functions — NCERT Class 11 Computer Science](/class/11/computer-science/solutions/cbse-functions-exercise-solutions).
