Skip to content
Computer ScienceCBSE Class 12 · Chapter 2

Functions in Python: CBSE Class 12 Computer Science Notes and Questions

Updated 14 October 2026 · Fact-checked

A function is a named block of code that runs when it is called. Class 12 covers built-in, module and user-defined functions, parameters and arguments, default and positional parameters, returning one or more values, the flow of execution, and local versus global scope. Board questions are mostly output prediction, error correction and short function-writing tasks.

What Functions is about

Functions is the second chapter of Unit 1. From here on, almost every program the board asks for is written as a function: "Write a function COUNT() that reads a text file...", "Write functions PUSH() and POP()...", "Write a function to insert a record...". So a sloppy header or a missing return costs marks in every later chapter too.

The syllabus lists exactly these ideas:

  • types of functions: built-in (len(), print(), int()), functions in a module (math.sqrt(), random.randint()) and user-defined functions
  • creating a user-defined function with def, its header, body and return
  • arguments (values in the call) and parameters (names in the header)
  • positional parameters (matched by order) and default parameters (used when the call leaves them out)
  • returning one value, several values (as a tuple) or nothing (None)
  • flow of execution: Python reads def lines without running the body, and the body runs only when the function is called
  • scope: local variables live inside a function, global ones at the top level, and the global statement lets a function change a global variable

Two ideas decide most output questions: whether the argument is mutable (a list changed inside a function stays changed) and whether a name inside a function is local or global.

Weightage: This chapter is part of Unit 1, Computational Thinking and Programming - 2, which carries 40 of the 70 theory marks together with Revision of Python Topics from Class XI, Exception Handling in Python, File Handling in Python and Stack.Source: CBSE Computer Science (083) syllabus 2026-27, distribution of marks, Unit 1 Computational Thinking and Programming - 2

Key concepts

Types of functions
NCERT section Class XI NCERT 7.2, 7.5

Built-in functions are always available without an import: len(), type(), int(), input(), print(), max(), round(). Functions defined in modules need the module imported first: import math then math.ceil(4.2), or from random import randint then randint(1, 6). User-defined functions are the ones you write with def. A function may take arguments and may return a value; one that has no return statement returns None.

Worked example

Classify each as built-in, module or user-defined, and give its value: len('abc'), max(3, 7, 1), math.sqrt(49) (after import math), round(3.14159, 2), int('25') + 5.

Try it first, then show the solutionSolution
  1. len() is built-in: 3. max() is built-in: 7.
  2. math.sqrt() is a module function and returns a float: 7.0.
  3. round() is built-in: 3.14. int() is built-in: int('25') + 5 = 30.

Answer: 3, 7, 7.0, 3.14, 30; only sqrt() is a module function. None of these is user-defined.

Defining and calling a function
NCERT section Class XI NCERT 7.3

A definition has a header and an indented body:

def function_name(parameter1, parameter2):
    statements
    return value

The header needs the keyword def, the name, round brackets (even if empty) and a colon. The body runs only when the function is called, e.g. function_name(10, 20). return sends a value back and ends the function at once; any lines after it in that path are skipped. If the body ends without return, the call gives None.

Worked example

Predict the output:

def f(n):
    if n % 2 == 0:
        return n // 2
    print('odd')
print(f(4), f(3))
Try it first, then show the solutionSolution
  1. Both arguments of print() are evaluated first, left to right.
  2. f(4): 4 is even, so it returns 2.
  3. f(3): 3 is odd, so it prints 'odd' and reaches the end without return, giving None.
  4. Only now does the outer print() run, showing 2 and None.

Answer: odd
2 None

Parameters, arguments, positional and default parameters
NCERT section Class XI NCERT 7.3.1-7.3.2

Parameters (formal parameters) are the names in the header; arguments (actual parameters) are the values in the call. Positional parameters are matched by order: the first argument goes to the first parameter, and so on. A default parameter has a value in the header (def power(base, exp=2):) and takes that value when the call leaves it out. Rule: once a parameter has a default, every parameter after it must also have one, so def f(a=1, b): is a SyntaxError. Too few or too many arguments in a call raise TypeError.

Worked example

Given def calc(p, q=2, r=3): return p * q + r, find calc(1), calc(1, 4) and calc(1, 4, 0). Which of the headers def g(a, b=1, c=2): and def g(a=1, b, c): is valid?

Try it first, then show the solutionSolution
  1. calc(1): p = 1, q = 2, r = 3, so 1 × 2 + 3 = 5.
  2. calc(1, 4): p = 1, q = 4, r = 3, so 7.
  3. calc(1, 4, 0): 1 × 4 + 0 = 4.
  4. In def g(a=1, b, c): non-default parameters follow a default one, so it is invalid; the first header is valid.

Answer: 5, 7, 4; only def g(a, b=1, c=2): is valid.

Returning values
NCERT section Class XI NCERT 7.3.3

A function can return any object. Writing return a, b returns one tuple (a, b), which can be unpacked: x, y = f(). A function without return (or with a bare return) gives None. Return ends the function: in a loop, return inside the loop stops the loop and the function together.

Worked example

Predict the output:

def change(a, b=5):
    a = a + b
    b = a - b
    return a, b
x, y = change(10)
print(x, y)
print(change(2, 3))
Try it first, then show the solutionSolution
  1. change(10): a = 10, b = 5 (default). a becomes 15, b becomes 15 - 5 = 10. Returns (15, 10), unpacked into x and y.
  2. change(2, 3): a becomes 5, b becomes 5 - 3 = 2. Returns the tuple (5, 2), which print() shows with brackets.

Answer: 15 10
(5, 2)

Flow of execution
NCERT section Class XI NCERT 7.4

Python runs a program from top to bottom, but a def statement only creates the function; its body is skipped until a call. On a call, control jumps to the function, runs its body, and comes back to the point just after the call (carrying the return value). A function can call another function defined later in the file, as long as both definitions have run before the first call happens.

Worked example

Predict the output:

def outer():
    print('A', end='')
    inner()
    print('C', end='')
def inner():
    print('B', end='')
print('S', end='')
outer()
print('E')
Try it first, then show the solutionSolution
  1. The two def statements only create the functions.
  2. The first statement that runs is print('S').
  3. outer() prints A, calls inner() which prints B, returns, and outer prints C.
  4. Back at the top level, 'E' is printed with a newline.

Answer: SABCE

Scope of a variable: local and global
NCERT section Class XI NCERT 7.4.1

A variable assigned inside a function is local: it exists only while that call runs and hides any global variable with the same name. A variable created at the top level is global and can be read inside a function. To assign to a global variable inside a function, declare it first with global name. If a function assigns to a name anywhere in its body, Python treats that name as local throughout the body, so reading it before the assignment raises UnboundLocalError.

Worked example

Predict the output:

total = 100
def add(x):
    global total
    total = total + x
    return total
def show():
    total = 5
    print('in show', total)
print(add(20), total)
show()
print(total)
Try it first, then show the solutionSolution
  1. add(20) is evaluated first: it changes the global total to 120 and returns 120. Then the second argument, total, is read: 120.
  2. show() creates a local total = 5, prints it, and leaves the global alone.
  3. The global total is still 120.

Answer: 120 120
in show 5
120

Passing mutable and immutable arguments
NCERT section Class XI NCERT 7.3 (passing lists and strings)

Python passes a reference to the object. If the function changes a mutable object in place (L.append(), L[i] = ..., D[k] = ...), the caller sees the change. If it rebinds the parameter (L = [0], n = n * 2), only the local name changes. Immutable arguments (numbers, strings, tuples) can never be changed in place, so the caller's variable is never affected.

Worked example

Predict the output:

def update(L, n):
    L.append(n)
    n = n * 2
    L = [0]
    return n
A = [1, 2]
m = 4
print(update(A, m), A, m)
Try it first, then show the solutionSolution
  1. L.append(4) changes the caller's list in place: A becomes [1, 2, 4].
  2. n = n * 2 rebinds the local n to 8; m stays 4.
  3. L = [0] rebinds only the local name L; A is not affected.
  4. The function returns 8.

Answer: 8 [1, 2, 4] 4

Functions in real life

Each concept, met in an everyday situation. Read the situation, answer the question in your own words, then compare with the model answer. The one-line hook is what to remember.

Default parameters

Suppose a juice shop's billing app charges 18 rupees GST on every 100 rupees unless the item is exempt, and the programmer writes def bill(price, gst=18):.

Complete the function so it returns the price with GST added, and find bill(200) and bill(200, 0).

Try it first, then show the solutionSolution
  1. def bill(price, gst=18):
        return price + price * gst / 100
    print(bill(200), bill(200, 0))
  2. bill(200) uses gst = 18: 200 + 36 = 236.0. bill(200, 0) overrides it: 200.0.

Answer: 236.0 200.0

Memory hook: A default is the shop's usual rate; passing an argument is the exception.

Global versus local scope

Imagine a cricket scoreboard program with a global score and a function four() that should add 4 runs each time a boundary is hit.

Why does def four(): score = score + 4 fail, and how do you fix it?

Try it first, then show the solutionSolution
  1. Because the function assigns to score, Python treats score as local in the whole function, so reading it on the right raises UnboundLocalError.
  2. Declaring it global makes the function update the scoreboard's variable:
    score = 0
    def four():
        global score
        score = score + 4
    four()
    four()
    print(score)

Answer: Add global score inside the function; after two boundaries the program prints 8.

Memory hook: To write on the shared scoreboard, say global first.

Mutable arguments

Suppose a teacher passes the class's marks list to a function grace(L) that adds 2 marks to everyone.

Will the teacher's original list change? Write the function.

Try it first, then show the solutionSolution
  1. Changing items by index changes the list object itself, which the caller shares.
  2. def grace(L):
        for i in range(len(L)):
            L[i] = L[i] + 2
    marks = [35, 48, 60]
    grace(marks)
    print(marks)

Answer: Yes. It prints [37, 50, 62].

Memory hook: Hand over a list and the function writes on your copy too.

Topics in this chapter

Functions: syntax and key facts

Function header
def name(p1, p2=default): followed by an indented body; brackets and colon are compulsory
Parameters with defaults must come after all parameters without defaults.
Return several values
return a, b, c returns the tuple (a, b, c); unpack with x, y, z = f()
A function with no return statement returns None.
Change a global inside a function
global count as the first statement that uses count, then count = count + 1
Without global, the assignment creates a local variable.
Three kinds of function
built-in (len(), max()), module (math.sqrt(), random.randint()), user-defined (def)
Module functions need an import first.
Mutable argument rule
In-place change (append, L[i] =, D[k] =) is seen by the caller; rebinding (L = ...) is not
Strings, numbers and tuples can never be changed through a parameter.

How the board asks Functions

The question patterns to expect, and the method that works for each.

Question typeHow it is askedMethod
Output of a function callA function with default parameters, a global variable or a list argument, followed by calls inside print() (2-3 marks).Track the call stack: for each call write the parameter values, trace the body, and carry the return value back; evaluate print()'s arguments left to right before printing anything.
Error correction in a functionA function with a wrong header, missing colon, misplaced default parameter or wrong return, to be rewritten with corrections underlined (2 marks).Check the header first (def, brackets, colon, defaults last), then indentation, then each statement.
Write a function on a list, tuple, string or dictionary"Write a function EOReplace(L) that...", "Write a function that takes a dictionary and returns..." (2-3 marks).Use exactly the name and parameters given; loop by index when you must change items in place; return or print as the question says.
Scope questionsIdentify local and global variables, or predict output when a function assigns to a name that is also global.If the function body assigns to a name and there is no global for it, that name is local in the whole function.
Concept questionsDifference between parameters and arguments, local and global scope, built-in and user-defined functions (1-2 marks).Define each term in one line and show it on a two-line example.

Tricks to remember Functions

Short memory aids. Say each one aloud once, then use it on a question the same day.

  • PA: Parameters in the header, Arguments in the call

    P comes first in the alphabet and first in the program (the def line); A comes later, at the call.

    Use it when: Definition questions on parameters and arguments.

  • Defaults go to the back of the queue

    Like latecomers in a line, parameters with defaults must stand after all those without.

    Use it when: Spotting the SyntaxError in headers such as def f(a=1, b):.

  • No return, gets None

    A function that falls off its end hands back None, so print(f()) prints whatever f prints and then None.

    Use it when: Output questions where a function prints instead of returning.

  • Assign inside = local everywhere inside

    One assignment to a name anywhere in a function makes it local from the first line of the function.

    Use it when: UnboundLocalError questions.

  • Change in place travels, rebinding stays home

    append, item assignment and += on a list travel back to the caller; L = something stays inside the function.

    Use it when: List-argument output questions.

Functions: board-level solved questions

Ordered from board level to HOTS. Cover the solution, write your own, then compare step by step.

Example 1: Case-swapping function · 2 marks · Short answerHarder board level

Predict the output:

def fun(s):
    k = len(s)
    m = ''
    for i in range(0, k):
        if s[i].isupper():
            m = m + s[i].lower()
        elif s[i].isalpha():
            m = m + s[i].upper()
        else:
            m = m + 'bb'
    print(m)
fun('school2@com')
Try it first, then show the solutionSolution
  1. All letters are lowercase, so each letter is turned to uppercase: SCHOOL ... COM.
  2. '2' and '@' are not letters, so each adds 'bb': 'bbbb' in all.
  3. Join in order: 'SCHOOL' + 'bbbb' + 'COM'.

Answer: SCHOOLbbbbCOM

Example 2: Rotate a list left · 3 marks · Short answerHOTS / competency

Predict the output:

def Lshift(Arr, n):
    L = len(Arr)
    for x in range(0, n):
        y = Arr[0]
        for i in range(0, L - 1):
            Arr[i] = Arr[i + 1]
        Arr[L - 1] = y
    print(Arr)
Lshift([10, 20, 30, 40, 12, 11], 2)
Try it first, then show the solutionSolution
  1. Each pass of the outer loop saves the first item, shifts every item one place left, and puts the saved item at the end.
  2. After pass 1: [20, 30, 40, 12, 11, 10].
  3. After pass 2: [30, 40, 12, 11, 10, 20].

Answer: [30, 40, 12, 11, 10, 20]

Example 3: Global versus local in one program · 3 marks · Short answerHarder board level

Predict the output:

a = 5
def tricky(a):
    a += 1
    print(a, end=' ')
c = 0
def counter():
    global c
    c += 1
tricky(a)
print(a)
for i in range(3):
    counter()
print(c)
Try it first, then show the solutionSolution
  1. Inside tricky, a is a parameter (local). It becomes 6 and is printed with a space after it.
  2. The global a is untouched, so print(a) shows 5 on the same line.
  3. counter() changes the global c each time; after three calls c = 3.

Answer: 6 5
3

Example 4: Spot the errors in a function · 2 marks · Short answerBoard level

Rewrite after correcting the errors (underline each correction):

def area(l=10, b)
    a = l * b
    Return a
print(area(5 4))
Try it first, then show the solutionSolution
  1. Non-default parameter after a default: write def area(l, b=10): (or give both defaults).
  2. Colon missing at the end of the header.
  3. Return must be lowercase return.
  4. Arguments must be separated by a comma: area(5, 4).

Answer:

def area(l, b=10):
    a = l * b
    return a
print(area(5, 4))
Output: 20

Example 5: Returning a tuple · 2 marks · Short answerBoard level

Predict the output:

def change(a, b=5):
    a = a + b
    b = a - b
    return a, b
r = change(1)
print(type(r), r[0])
Try it first, then show the solutionSolution
  1. change(1): a = 1 + 5 = 6, b = 6 - 5 = 1; it returns (6, 1).
  2. r holds the tuple, so type(r) is tuple and r[0] is 6.

Answer: <class 'tuple'> 6

Example 6: Assertion-reason on default parameters · 1 mark · Assertion-reasonHOTS / competency

Assertion (A): The header def show(x=0, y): causes a SyntaxError.
Reason (R): Default parameters must be written before the parameters that have no default.
(a) Both true, R explains A (b) Both true, R does not explain A (c) A true, R false (d) A false, R true

Try it first, then show the solutionSolution
  1. A is true: a non-default parameter follows a default one.
  2. R states the rule the wrong way round: defaults must come after non-default parameters. So R is false.

Answer: (c) A is true but R is false.

Example 7: Function on a dictionary · 3 marks · Short answerHarder board level

Write a function topper(D) that takes a dictionary of names and marks and returns the name with the highest marks. Call it with the dictionary built from names ['A', 'B'] and marks [90, 80].

Try it first, then show the solutionSolution
  1. Build the dictionary by pairing index by index; then keep the best name seen so far.
  2. def makeDict(names, marks):
        D = {}
        for i in range(len(names)):
            D[names[i]] = marks[i]
        return D
    def topper(D):
        best = None
        for name in D:
            if best is None or D[name] > D[best]:
                best = name
        return best
    D = makeDict(['A', 'B'], [90, 80])
    print(D, topper(D))

Answer: {'A': 90, 'B': 80} A

Example 8: Which call raises an error? · 1 mark · MCQHOTS / competency

For def calc(p, q=2, r=3): return p * q + r, which call raises an error? (a) calc(1) (b) calc(1, 4) (c) calc() (d) calc(1, 4, 0)

Try it first, then show the solutionSolution
  1. p has no default, so at least one argument is needed.
  2. calc() gives no value for p: TypeError (missing 1 required positional argument).

Answer: (c) calc()

Case-study practice (Section E style)

Read the situation, then answer every part. In the board paper this is a 4-mark question split into 1 + 1 + 2 marks.

A marks utility for the class teacher

Suppose a class teacher keeps marks in a list and writes small functions to process them:

def grace(L, g=2):
    for i in range(len(L)):
        L[i] = L[i] + g
def average(L):
    return sum(L) / len(L)
marks = [35, 48, 61]
  1. (i) · 1 mark

    Name one built-in function used in these functions.

    Answer

    Answer: Any one of range(), len(), sum().

    They need no import and no def.

  2. (ii) · 1 mark

    After grace(marks), what is marks?

    Answer

    Answer: [37, 50, 63]

    g takes the default 2, and the list is changed in place, so the caller sees it.

  3. (iii) · 2 marks

    If instead grace(marks, 5) is called on the original list, what does print(average(marks)) show? Explain.

    Answer

    Answer: 53.0

    g = 5 overrides the default, and marks becomes [40, 53, 66] in place. average() returns 159 / 3, and / always gives a float, so 53.0 is printed.

Where the marks are

How a typical answer is split into step marks. Show every step: a right final answer alone rarely earns full marks.

Find the output: def power(base, exp=2): return base ** exp and print(power(3), power(2, 5)). [2 marks] (2 marks)

StepMarks
power(3) uses the default exp = 2: 91
power(2, 5) = 32, printed as 9 321

Write a function EOReplace(L) that replaces each even number in the list L by half of it and each odd number by double of it. For L = [10, 7, 4, 9] the list should become [5, 14, 2, 18]. [3 marks] (3 marks)

StepMarks
Correct header def EOReplace(L):0.5
Loop over indices with range(len(L))1
Correct even/odd test and assignments L[i] = L[i] // 2 and L[i] = L[i] * 21.5

Write a function stats(L) that returns the smallest value, the largest value and the average of a list of numbers, and show how to call it and print the three values for [4, 9, 2, 7]. [4 marks] (4 marks)

StepMarks
Header and computing min, max and sum(L) / len(L)1.5
Returning the three values together1
Call with unpacking into three variables1
Printing them: 2 9 5.50.5

Write a function makeDict(names, marks) that takes two lists of equal length and returns a dictionary with names as keys and marks as values; then write a function topper(D) that returns the name with the highest marks. Show both calls. [5 marks] (5 marks)

StepMarks
makeDict header, empty dictionary and loop over indices1
D[names[i]] = marks[i] and return D1
topper header and finding the highest value (loop or max with key)1.5
Returning the name0.5
Correct calls and printing1

Where students lose marks in Functions

The slips examiners see most often, and what to write instead.

  • Mistake: Printing inside the function when the question asks it to return a value (or the reverse)

    "returns the count" and "displays the count" are marked differently.

    Wrong working

    def COUNT(L):
    c = 0
    ...
    print(c)

    Right working

    def COUNT(L):
    c = 0
    ...
    return c

    Do this: Underline the verb in the question: returns means return, displays or prints means print().

    Usually costs: Half to 1 mark

  • Mistake: Changing the function name or parameters given in the question

    The question fixes the header, e.g. EOReplace(L); a different name or an extra input() inside the function does not match it.

    Do this: Copy the header exactly as given, and take data from the parameters, not from input(), unless the question asks for input.

    Usually costs: Half a mark

  • Mistake: Forgetting that print() evaluates all its arguments before printing

    When an argument is a call that itself prints, its output comes first, on its own line.

    Wrong working

    print(f(4), f(3)) gives 2 odd None

    Right working

    odd
    2 None

    Do this: Evaluate every argument (running any prints inside) and only then write the line print() itself produces.

    Usually costs: 1 mark

  • Mistake: Assuming a function cannot change a list passed to it

    Students apply the rule for numbers to lists.

    Wrong working

    A = [1, 2]; after update(A, 4), A is still [1, 2]

    Right working

    L.append(n) changes the shared list, so A is [1, 2, 4]

    Do this: Mark every line in the function as in-place change or rebinding before you trace.

    Usually costs: 1 mark

  • Mistake: Using a loop variable instead of an index to change list items

    for x in L: x = x * 2 changes only x, never the list.

    Wrong working

    for x in L:
    x = x * 2

    Right working

    for i in range(len(L)):
    L[i] = L[i] * 2

    Do this: When a function must modify the list itself, loop over range(len(L)) and assign to L[i].

    Usually costs: 1-2 marks in a function-writing question

NCERT exercise guide: Functions

What each exercise in the NCERT chapter tests, how to approach it, and a question of the same kind solved step by step. Questions here are written in our own words.

Class XI NCERT Chapter 7 (Functions) exercises: output and error questions

What it tests: Predicting output of programs with functions, default parameters and global variables; finding errors in function definitions.

How to approach it: Trace each call separately, writing the parameter values on entry and the return value on exit.

Same kind as the output questions in Chapter 7

Predict the output:

v = 10
def g():
    print(v)
def h():
    print(w)
    w = 3
g()

What happens if h() is also called?

Show the solutionSolution
  1. g() only reads v, so it finds the global v = 10 and prints 10.
  2. h() assigns w later in its body, so w is local in the whole function; print(w) reads it before it has a value.

Answer: 10; calling h() raises UnboundLocalError.

Class XI NCERT Chapter 7 (Functions) exercises: programming questions

What it tests: Writing user-defined functions that take parameters and return results, e.g. counting, checking and computing.

How to approach it: Decide the parameters and the return value first; then write the loop or formula; finally test with one call.

Same kind as the function-writing exercises

Write a function countv(s) that returns the number of vowels in the string s, and call it for 'Education'.

Show the solutionSolution
  1. def countv(s):
        c = 0
        for ch in s.lower():
            if ch in 'aeiou':
                c += 1
        return c
    print(countv('Education'))
  2. Vowels in 'education': e, u, a, i, o.

Answer: 5

Practice questions on Functions

Write each answer on paper first. Open the hint only if you are stuck, and the answer only when you have finished.

  1. Q1 · 2 marks · Short answerHOTS / competency

    Predict the output:

    def update(L, n):
        L += [n]
        n = n + 1
        L = L + [0]
        return n, L
    A = [1, 2]
    m = 4
    print(update(A, m), A, m)
    Hint

    Separate in-place changes from rebinding: += on a list works in place, L = L + [0] builds a new list.

    Answer

    (5, [1, 2, 4, 0]) [1, 2, 4] 4 (L += [n] extends A itself; L = L + [0] makes a new local list that only the returned tuple holds; m is never changed)

  2. Q2 · 1 mark · MCQBoard level

    Which statement about the global keyword is correct? (a) It is needed to read a global variable inside a function. (b) It is needed to assign to a global variable inside a function. (c) It makes a variable visible in other modules. (d) It creates a new local variable.

    Hint

    Reading needs nothing.

    Answer

    (b) It is needed to assign to a global variable inside a function.

  3. Q3 · 2 marks · Short answerBoard level

    Write a function SUMDIGIT(n) that returns the sum of the digits of a positive integer n. Show the call for 4072.

    Hint

    Use % 10 and // 10 in a loop.

    Answer
    def SUMDIGIT(n):
        s = 0
        while n > 0:
            s += n % 10
            n //= 10
        return s
    print(SUMDIGIT(4072))

    Output: 13

  4. Q4 · 2 marks · Short answerHarder board level

    Predict the output:

    def f(x, y=3):
        x = x + y
        return x * y
    print(f(2), f(2, 1), f(f(1, 1)))
    Hint

    Work out the inner call first in f(f(1, 1)).

    Answer

    15 3 15 (f(2) = (2 + 3) × 3 = 15; f(2, 1) = 3 × 1 = 3; f(1, 1) = 2 × 1 = 2, so f(f(1, 1)) = f(2) = 15)

  5. Q5 · 3 marks · Short answerHarder board level

    Write a function COUNTWORDS(s) that returns a dictionary giving how many times each word occurs in the string s. Show the result for 'to be or not to be'.

    Hint

    split() then get(w, 0) + 1.

    Answer
    def COUNTWORDS(s):
        D = {}
        for w in s.split():
            D[w] = D.get(w, 0) + 1
        return D
    print(COUNTWORDS('to be or not to be'))

    Output: {'to': 2, 'be': 2, 'or': 1, 'not': 1}

  6. Q6 · 2 marks · Short answerBoard level

    Identify the local and global variables in this program and give its output:

    x = 50
    def func(y):
        z = x + y
        return z
    print(func(5))
    Hint

    Parameters are local too.

    Answer

    Global: x. Local: y (parameter) and z. Output: 55

  7. Q7 · 2 marks · Short answerHarder board level

    Predict the output:

    def m(s):
        r = ''
        for i in range(len(s) - 1, -1, -2):
            r = r + s[i]
        return r.upper()
    print(m('python'))
    Hint

    Indices 5, 3, 1.

    Answer

    NHY (s[5] = 'n', s[3] = 'h', s[1] = 'y')

  8. Q8 · 2 marks · Short answerBoard level

    Write a function INDEX_LIST(L) that returns a list of the indices of all non-zero items of L. For L = [12, 4, 0, 11, 0, 56] it should return [0, 1, 3, 5].

    Hint

    Loop over range(len(L)).

    Answer
    def INDEX_LIST(L):
        R = []
        for i in range(len(L)):
            if L[i] != 0:
                R.append(i)
        return R
    print(INDEX_LIST([12, 4, 0, 11, 0, 56]))

    Output: [0, 1, 3, 5]

  9. Q9 · 2 marks · Short answerHOTS / competency

    Predict the output and explain:

    num = 1
    def add_one():
        num = num + 1
        return num
    print(add_one())
    Hint

    The assignment makes num local.

    Answer

    UnboundLocalError: because add_one() assigns to num, num is local throughout the function, and num + 1 reads it before it has a value. Adding global num would print 2.

  10. Q10 · 3 marks · Short answerHarder board level

    Write a function stats(L) that returns the minimum, maximum and average of L, and print the three values for [4, 9, 2, 7].

    Hint

    Return three values as one tuple.

    Answer
    def stats(L):
        return min(L), max(L), sum(L) / len(L)
    lo, hi, av = stats([4, 9, 2, 7])
    print(lo, hi, av)

    Output: 2 9 5.5

Test your recall

Answer in your head or on paper first, then open the card. Pulling an answer out of memory makes it stick far better than re-reading.

  1. 1.What is the difference between a parameter and an argument?Show answer

    A parameter is the name in the function header; an argument is the value passed in the call.

  2. 2.What does a function return if it has no return statement?Show answer

    None.

  3. 3.Why is def f(a=2, b): an error?Show answer

    A parameter without a default cannot follow one with a default (SyntaxError).

  4. 4.What type is returned by return x, y?Show answer

    A tuple (x, y).

  5. 5.When is the global keyword needed?Show answer

    When a function assigns to a global variable; reading a global needs no declaration.

  6. 6.Give one example each of a built-in, a module and a user-defined function.Show answer

    len(); math.sqrt() or random.randint(); any function you write with def, such as area(r).

  7. 7.Does a function body run when Python reads its def statement?Show answer

    No. def only creates the function; the body runs on each call.

  8. 8.What error do you get if a function reads a name before assigning it locally?Show answer

    UnboundLocalError.

Best order to study it

  1. Types of functions and how to call module functions.
  2. Writing a header and body; return versus print.
  3. Positional and default parameters, with the defaults-last rule.
  4. Returning several values as a tuple.
  5. Flow of execution with nested calls.
  6. Scope: local, global and the global statement; then mutable arguments.

Quick revision checklist

The night before the exam: can you do each of these without looking?

  • Three types: built-in, module (needs import), user-defined (def).
  • Header: def name(params):; body indented; called by name(args).
  • Parameters in the header, arguments in the call; positional arguments match by order.
  • Default parameters must come after non-default ones.
  • return a, b returns a tuple; no return gives None; return ends the function.
  • def does not run the body; a call does, and control comes back to the caller.
  • Assigned inside a function = local, unless declared global.
  • Lists and dictionaries changed in place inside a function stay changed for the caller.

Functions: frequently asked questions

Are keyword arguments in the CBSE Class 12 syllabus?

The 2026-27 syllabus names arguments and parameters, default parameters and positional parameters. Keyword arguments are not named separately, so this page focuses on positional and default parameters.

How many marks does the Functions chapter carry?

No separate figure is given. It is part of Unit 1 (40 of 70 theory marks). Functions also appear inside file-handling, stack and Python-SQL questions, because those programs are written as functions.

What is the difference between local and global variables?

A local variable is created inside a function and exists only during that call. A global variable is created at the top level and can be read anywhere; a function must declare it global before assigning to it.

Can a Python function return more than one value?

Yes. return a, b returns a single tuple holding both values, which the caller can unpack: x, y = f().

What is flow of execution?

The order in which statements run: top to bottom, skipping function bodies at def, jumping into a body at each call and returning to the statement after the call.

Based on: CBSE Computer Science (083) syllabus 2026-27; NCERT Computer Science, Textbook for Class XI (Reprint 2026-27)