Chapter 07: Functions

CBSE Class 11 Computer Science

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:

  1. Built-in functions
  2. 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:

  • def tells 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:

  1. Python encounters function call
  2. Control jumps to function definition
  3. Statements inside function execute
  4. 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:

  • n is a parameter
  • 5 and 10 are 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:

  • return sends 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:

  • x exists only inside test()
  • 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:

  • x is 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 root
  • math.factorial() calculates factorial
  • math.pi gives value of Ο€

Selective Import

from math import sqrt, pi

print(sqrt(25))
print(pi)

Commonly Used Standard Library Modules (NCERT)

  • math – mathematical operations
  • random – random number generation
  • statistics – mean, median, mode
  • time – time-related functions

Example: random Module

import random

print(random.randint(1, 6))

Used in:

  • games
  • simulations
  • sampling

Key Conceptual Takeaways

  1. In programming, functions are used to achieve modularity and reusability.
  2. 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.
  3. 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.
  4. An argument is a value passed to the function during function call which is received in a parameter defined in function header.
  5. Python allows assigning a default value to the parameter.
  6. A function returns value(s) to the calling function using return statement.
  7. Multiple values in Python are returned through a Tuple.
  8. Flow of execution can be defined as the order in which the statements in a program are executed.
  9. The part of the program where a variable is accessible is defined as the scope of the variable.
  10. 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.
  11. 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.
  12. The Python standard library is an extensive collection of functions and modules that help the programmer in the faster development of programs.
  13. A module is a Python file that contains definitions of multiple functions.
  14. A module can be imported in a program using import statement.
  15. Irrespective of the number of times a module is imported, it is loaded only once.
  16. To import specific functions in a program from a module, from statement can be used.
Page last updated: 19-Jan-2026
Last Change: "some changes for timezone and git checkin history pull by hugo" (#b34f1bc)