Free tutorials & notes in Hindi & English · Clean code examples 🧰 Free PDF & Image Tools →
🔁 Unit 2 – Flow of Control & Functions  ·  Lesson 18

User-defined Functions

Why functions?

A function is a named block of code that does one specific task and runs only when it is called. Instead of writing the same 10 lines in five places, we write them once in a function and call it five times.

♻️
ReusabilityWrite once, use many times.
🧩
ModularityBig program split into small, clear parts (decomposition).
🐞
Easy debuggingTest and fix each function separately.
📖
Readabilitycalculate_gst(price) is easier to read than the formula.
Benefits of functions

Types of functions

🧰
Built-inAlways available: print(), input(), len(), max(), int(), round().
📦
In modulesNeed import: math.sqrt(), random.randint(), statistics.mean().
✍️
User-definedWritten by you with def.
Three kinds of functions in Python

Defining and calling a function

Syntax
def function_name(parameters):
    """optional docstring"""
    statements
    return value          # optional
Python
def greet():
    print('Good morning!')
    print('Welcome to Class XI')

greet()          # call the function
greet()          # call it again
Good morning! Welcome to Class XI Good morning! Welcome to Class XI

The def line is the function header; the indented lines are the function body. Defining a function does not run it — calling it with greet() does.

Parameters and arguments

Python
def area_rectangle(length, breadth):     # parameters
    return length * breadth

a = area_rectangle(12, 5)                # arguments
print('Area =', a)
print('Two rooms =', area_rectangle(4, 3) + area_rectangle(5, 4))
Area = 60 Two rooms = 32
area_rectangle(12, 5)arguments (actual values)length = 12, breadth = 5parameters receive themreturn 60value sent back
Arguments are copied into parameters in order (positional arguments)

Returning a value

return sends a value back to the caller and ends the function immediately. A function without return gives back None.

Python
def show(x):
    print('Value is', x)      # no return statement

result = show(10)
print('Function returned', result)
Value is 10 Function returned None

Function that prints

  • Shows result on screen
  • Result cannot be used further
  • Returns None

Function that returns

  • Gives result back to the caller
  • Can be stored, added, printed later
  • More useful and reusable
Prefer return for calculations

Default and keyword arguments

Python
def simple_interest(p, r=8, t=1):        # r and t have default values
    return p * r * t / 100

print(simple_interest(5000))             # r=8, t=1
print(simple_interest(5000, 10))         # t=1
print(simple_interest(5000, 10, 3))
print(simple_interest(t=2, p=1000))      # keyword arguments, any order
400.0 500.0 1500.0 160.0
  • Positional arguments are matched by position.
  • Default arguments are used when a value is not passed (r=8).
  • Keyword arguments name the parameter (t=2, p=1000), so order does not matter.

Returning many values

Python can return several values separated by commas; they come back as a tuple that can be unpacked.

Python
def stats(numbers):
    total = sum(numbers)
    avg = total / len(numbers)
    return total, avg, max(numbers)       # returns a tuple

t, a, m = stats([45, 78, 62, 91])
print('Total:', t, 'Average:', a, 'Highest:', m)
Total: 276 Average: 69.0 Highest: 91

Flow of execution

Python reads the file top to bottom. When it reaches a def, it only remembers the function. When the function is called, control jumps into the body, runs it, and comes back to the line after the call.

Python
print('1. Start')

def square(x):
    print('3. Inside square')
    return x * x

print('2. Before calling')
y = square(6)
print('4. Back, y =', y)
1. Start 2. Before calling 3. Inside square 4. Back, y = 36
Main programsquare()1. Start, 2. Before callingsquare(6)3. Inside squarereturn 364. Back, y = 36
Control goes into the function and returns

Passing mutable and immutable arguments

If a function changes a list (mutable) passed to it, the change is visible outside. Re-assigning an int or string inside the function does not affect the caller.

Python
def add_bonus(marks_list, bonus):
    for i in range(len(marks_list)):
        marks_list[i] += bonus       # list is mutable: caller sees change

def change_number(n):
    n = n + 100                      # int is immutable: caller does not see change

m = [70, 80]
add_bonus(m, 5)
x = 10
change_number(x)
print(m, x)
[75, 85] 10

Solved programs

Function returning True/False

Python
def is_prime(n):
    if n < 2:
        return False
    for d in range(2, int(n ** 0.5) + 1):
        if n % d == 0:
            return False          # return ends the function at once
    return True

print([x for x in range(1, 30) if is_prime(x)])
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29]

One function calling another

Python
def factorial(n):
    f = 1
    for i in range(2, n + 1):
        f *= i
    return f

def nCr(n, r):                      # a function calling another function
    return factorial(n) // (factorial(r) * factorial(n - r))

print('5! =', factorial(5))
print('Ways to choose 3 from 7 =', nCr(7, 3))
5! = 120 Ways to choose 3 from 7 = 35

Docstring

Python
def celsius_to_f(c):
    """Convert Celsius to Fahrenheit."""
    return c * 9 / 5 + 32

print(celsius_to_f(37))
print(celsius_to_f.__doc__)
98.6 Convert Celsius to Fahrenheit.

Summary & practice

  • def name(params): defines; name(args) calls.
  • return sends a value back and ends the function; no return → None.
  • Default and keyword arguments make calls flexible.
  • Return several values as a tuple.
✅ Practice

Write functions: (1) is_even(n) returning True/False, (2) count_vowels(text), (3) power(base, exp=2), (4) min_max(lst) returning both values. Predict: def f(a, b=3): return a * b → print(f(4), f(4, 5), f(b=2, a=7)).

Answer: 12 20 14

Frequently Asked Questions

What is the difference between a parameter and an argument?
A parameter is the variable written in the function definition (def area(l, b)). An argument is the actual value passed when calling it (area(12, 5)).
What does a function return if there is no return statement?
It returns None automatically.
Can default parameters come before normal parameters?
No. Parameters with default values must come after the ones without defaults. def f(a, b=2) is valid, def f(a=1, b) is a SyntaxError.
← Class 11 Computer Science
🔗

Share this topic with a friend

यह topic किसी दोस्त को भेजें

Found it useful? Send it to a classmate learning the same thing.

अच्छा लगा? जो दोस्त यही सीख रहा है, उसे भेज दीजिए।

Next topicScope & Modules (math, random) Your progress: 18 / 29 (62%) · Lesson 19 / 29 Continue →

How was this lesson?

Your feedback helps us make the content better.

Write a review or suggestion (optional)

After approval, your name and city may appear publicly with your review. Please do not write your email or phone number.

▶ CodingEasily on YouTube

Learn with video lessons in easy Hindi

Featured video: RDBMS Part 3 – Class XI Commerce IT

▶ Subscribe – it’s free