📌 Snapshot
- Functions are the primary tool for achieving modularity and reusability in Python programs.
- User-defined functions differ from Python's built-in functions and the standard library; the function lifecycle covers definition, arguments/parameters, return values, and flow of execution.
- Variable scope is either global or local — a concept NTA directly tests through code-tracing questions.
- Sections on Python's standard library (built-in functions, and the math, random, and statistics modules) are directly examinable as fill-in-the-function or output-prediction items.
- Functions underpin every Python programming task; understanding default parameters, scope rules, and module import syntax is essential for the CUET programming section.
📖 Detailed Notes
2.1 Core concepts
- Modular programming is the process of dividing a program into separate, independent blocks of code (sub-problems) with different names and specific functionalities. Program 7-1 (without functions) is contrasted with Program 7-2 (with functions) to illustrate this. (NCERT §7.1, p. 143)
- Function definition: A function is a named group of instructions that accomplishes a specific task when invoked. It can be called repeatedly from different places without rewriting the code. (NCERT §7.2, p. 145)
- Advantages of functions: (a) Increases readability by organising code into logical blocks; (b) Reduces code length — same code is not repeated; (c) Increases reusability — a function can be called from another function or another program; (d) Enables parallel development by dividing work among team members. (NCERT §7.2.1, p. 146)
- User-defined functions (UDF): Functions defined by the programmer to meet specific requirements. Syntax begins with the keyword
def, followed by function name, optional parameter list in parentheses, and a colon. The body is indented. A function may or may not have parameters; it may or may not return a value. Function name must be unique and follows identifier naming rules. Function header always ends with a colon (:). (NCERT §7.3, §7.3.1, p. 147) - Arguments vs. Parameters: An argument is a value passed to the function during the function call. A parameter is the variable in the function header that receives the argument. Both refer to the same memory object; they share the same
id()before any reassignment inside the function. (NCERT §7.3.2, p. 148–149) - String as parameters: Functions can accept string arguments, not just numeric ones. The
+operator is used to concatenate strings inside a function (Program 7-8). (NCERT §7.3.2(A), p. 151–152) - Default parameter: Python allows assigning a predecided value to a parameter. The default value is used when the function call does not supply the corresponding argument. Default parameters must be trailing parameters — if one parameter has a default value, all parameters to its right must also have default values. A function argument can also be an expression (e.g.,
mixedFraction(num+5, deno+5)), evaluated before the call. (NCERT §7.3.2(B), p. 152–153) - Functions returning values: Functions that do not use
returnare called void functions. Thereturnstatement returns control to the calling function and optionally returns one or more values. Multiple return values are packed as a tuple. (NCERT §7.3.3, p. 154–156) - Flow of execution: Python executes statements top to bottom. When a function definition is encountered, its body is skipped until the function is called. When a call is encountered, control jumps to the function body, executes it, then returns to the point of the call. A function must be defined before it is called, otherwise a
NameErroris raised. (NCERT §7.3.4, p. 155) - Scope of a variable: The part of the program where a variable is accessible is its scope. (NCERT §7.4, p. 158)
- Global variable: Defined outside any function or block; accessible throughout the program. Any modification is permanent and affects all functions. (NCERT §7.4(A), p. 158)
- Local variable: Defined inside a function or block; accessible only within that function; exists only while the function executes. A local variable with the same name as a global variable hides the global inside that function. To modify a global variable inside a function, prefix it with the
globalkeyword. (NCERT §7.4(B), p. 158–160) - Python Standard Library: A large collection of built-in functions and modules. Functions like
input(),print(),int(),abs(),max(),min(),pow(),divmod(),sum(),len()are built-in. Additional functionality is available through modules. (NCERT §7.5, §7.5.1, p. 160–162) - Modules: A module is a
.pyfile containing a collection of function definitions. Import syntax:import modulename. To call a function from a module:modulename.functionname(). Thefromstatement imports specific functions, allowing direct calls without the module prefix. A module is loaded only once regardless of how many times it is imported. Key built-in modules:math,random,statistics. (NCERT §7.5.2, p. 162–168) - math module:
math.ceil(x)— ceiling value;math.floor(x)— floor value;math.fabs(x)— absolute value (float);math.factorial(x)— factorial;math.gcd(x,y)— greatest common divisor;math.pow(x,y)— x raised to y;math.sqrt(x)— square root;math.sin(x)— sine in radians. (NCERT §7.5.2, Table 7.2, p. 163–164) - random module:
random.random()— random float in [0.0, 1.0);random.randint(x,y)— random integer between x and y (inclusive);random.randrange(y)— random integer between 0 and y;random.randrange(x,y)— random integer between x and y. (NCERT §7.5.2, Table 7.3, p. 164–165) - statistics module:
statistics.mean(x)— arithmetic mean;statistics.median(x)— median;statistics.mode(x)— mode (most repeated value). (NCERT §7.5.2, Table 7.4, p. 165) - Docstring: A multiline comment (
"""...""") added as the first line of a module or function to describe it. Stored in the__doc__attribute, accessed viaprint(modulename.__doc__). (NCERT §7.5.2, p. 167–168)
2.2 Definitions to memorise
| Term | Definition | Page |
|---|---|---|
| Function | A named group of instructions that accomplishes a specific task when invoked | 145 |
| Modular programming | Dividing a program into separate independent blocks of code (sub-problems) with different names and specific functionalities | 145 |
| User-defined function | A function defined by the programmer to achieve a specific task as per requirement | 147 |
| Argument | A value passed to the function during the function call | 148 |
| Parameter | A variable in the function header that receives the argument value | 148 |
| Default parameter | A parameter with a predecided value used when no corresponding argument is supplied in the function call | 152 |
| Void function | A function that does not return any value (performs task and displays results internally) | 154 |
| return statement | Statement that returns control (and optionally value/s) from the function to the calling code | 154 |
| Flow of execution | The order in which statements in a program are executed | 155 |
| Scope of a variable | The part of the program where a variable is accessible | 158 |
| Global variable | A variable defined outside any function or block; accessible throughout the program | 158 |
| Local variable | A variable defined inside a function or block; accessible only within that function; ceases to exist after function returns | 158 |
| Module | A Python (.py) file containing a collection of function definitions | 162 |
| Docstring | A multiline string ("""...""") used to describe a module or function; stored in __doc__ |
167 |
from statement |
Used to import only specific function(s) from a module, allowing direct call without module prefix | 166 |
| Built-in function | A function pre-defined in Python and available without explicit import (e.g., print, len, abs) |
161 |
def keyword |
Reserved word that introduces a function definition in Python | 147 |
| Function header | The def name(parameters): line that introduces a function definition |
147 |
| Function body | The indented block of statements that executes when the function is called | 147 |
global keyword |
Used inside a function to indicate that a name refers to a module-level (global) variable for assignment | 159 |
math module |
Standard library module providing mathematical functions like sqrt, floor, ceil, factorial, gcd |
163 |
random module |
Standard library module providing pseudo-random number generators like random(), randint(), randrange() |
164 |
statistics module |
Standard library module providing mean, median, mode |
165 |
__doc__ |
Special attribute that stores the docstring of a module or function | 167 |
| Function call | An expression that invokes a function with optional arguments | 145 |
| Reusability | Property of functions that allows the same code to be used from multiple call sites | 146 |
2.3 Diagrams / processes to remember
- Figure 7.2 — Calculation of the cost of the tent (p. 144): Illustrates how a single program is broken into three named blocks (
cyl(h,r),con(l),post_tax_price()), motivating the concept of modular programming. - Figure 7.3 — Argument and parameter pointing to the same value (p. 148): Shows that
num(argument) andn(parameter) both refer to the same memory object (value 5) before any reassignment inside the function. - Figure 7.4 — ID of argument and parameter before and after increment (p. 150): Before increment,
NumberandNumshare the sameid. Afternum = num + 5,Numpoints to a new object (id changes), whileNumberremains unchanged. Demonstrates Python's immutability for integers. - Figure 7.5 — Order of execution of statements (p. 156): Shows numbered execution order for two programs with function calls — the interpreter skips function definitions and executes them only when called.
- Figure 7.6 — Scope of a variable (p. 158): Tree diagram showing Variable Scope branching into Global Scope and Local Scope.
- Figure 7.7 — Types of functions (p. 160): Tree showing Function branching into Standard Library (Built-in, Module) and User Defined.
- Table 7.1 — Commonly used built-in functions (p. 161–162):
abs,divmod,max,min,pow,sum,lenwith arguments, return types, and examples. Must be memorised. - Tables 7.2, 7.3, 7.4 — math, random, statistics module functions (p. 163–165): Key functions with syntax, arguments, return values, and example outputs.
2.4 Common confusions / NTA trap points
- Argument vs. Parameter confusion: NTA often gives a function call and asks which variable is the "argument" and which is the "parameter." Remember: argument is at the call site; parameter is in the function header. They can have the same name (Program 7-6), which trips students into thinking they are different variables.
- Default parameter placement rule: Students confuse which parameters can have defaults. The rule is that default parameters must be trailing —
def f(a, b=1)is correct butdef f(a=1, b)is incorrect. NTA presents incorrect headers (likedef calcInterest(principal=1000, rate, time=5)) as distractors. globalkeyword omission: A common trap is a function that reads a global variable without issue, but fails when it tries to reassign it without theglobalkeyword. Students often assume reading and writing a global variable work the same way inside a function — they do not.importvs.from ... import: When usingimport math, the call must bemath.sqrt(x). When usingfrom math import sqrt, the call is simplysqrt(x). NTA tests whether students know that the module prefix is dropped when usingfrom.- Void function vs. returning
None: A void function still technically returnsNonein Python. NTA may ask "what does a function that has noreturnstatement return?" — the answer isNone, not "nothing" or "error." math.pow(x,y)vs. built-inpow(x,y)(NCERT Table 7.1 and Table 7.2, p. 162-163).math.pow()always returns a float; the built-inpow()returns an integer when both arguments are integers.pow(x,y,z)also computes(x**y) % z, whichmath.pow()cannot do.- A function without
returnreturnsNone(NCERT §7.3.3, p. 154). NTA distractor: "no return → returns 0" — false. from module import *is discouraged but legal (NCERT §7.5.2(C), p. 166). It imports all functions; NCERT mentions star import as an option but recommends specific imports.- Multiple return values are packed as a tuple (NCERT §7.3.3, p. 154-156). A
return a, bactually returns the tuple(a, b); the caller can unpack withx, y = func(). - Function must be defined BEFORE the call (NCERT §7.3.4, p. 155). Forward references raise
NameError. NTA distractor may suggest "Python supports hoisting" — false. - Local variables die when the function returns (NCERT §7.4(B), p. 158-159). They cannot be accessed after the function ends. NTA traps may show post-function access of a local.
🎯 Practice MCQs
First 3 questions free · create a free account to unlock the rest — answers & explanations included, no payment needed
Q1. Which of the following is the correct syntax for defining a user-defined function in Python?
▸ Show answer & explanation
Answer: B
Python uses the keyword `def` to begin every function definition, followed by the function name, parameter list in parentheses, and a colon. Options A, C, and D use keywords that are not part of Python syntax. ---
Q2. Consider the following code: ```python num = 10 def myFunc(): num = 20 print(num) myFunc() print(num) ``` What will be the output?
▸ Show answer & explanation
Answer: C
Inside `myFunc()`, `num = 20` creates a local variable that shadows the global `num = 10`. The local `num` (20) is printed during the function call. After the function returns, the global `num` (10) is printed. Option A is wrong because the global `num` is not modified without the `global` keyword. ---
Q3. Which of the following statements about default parameters in Python is **correct**?
▸ Show answer & explanation
Answer: C
Python requires that once a parameter is given a default value, all parameters to its right must also have default values. Placing a default parameter before a non-default one (as in option A) produces a `SyntaxError`. Options B and D are factually wrong. ---
🔒 12 more practice MCQs
Create a free account to unlock every MCQ in this chapter — answers and explanations included. No payment needed.
Already registered? Just log in and they'll all appear here.
Q4. Assertion (A): In Program 7-5 of the NCERT textbook, before the increment operation inside `incrValue()`, the `id()` of the argument `number` and the parameter `num` are the same. Reason (R): When a function is called, the argument and the corresponding parameter refer to the same memory object.
▸ Show answer & explanation
Answer: A
When `incrValue(number)` is called, both `number` (argument) and `num` (parameter) point to the same integer object, so `id(number) == id(num)`. After `num = num + 5`, `num` is reassigned to a new object, so its `id` changes. Both the assertion and the reason are correct and the reason directly explains the assertion. ---
Q5. Match the following built-in functions with their correct descriptions: | Function | Description | |---|---| | P. `divmod(7, 2)` | 1. Returns `(3, 1)` — a tuple of quotient and remainder | | Q. `abs(-5.7)` | 2. Returns `5.7` — absolute value | | R. `len("Patience")` | 3. Returns `8` — count of elements | | S. `max([1, 2, 3, 4])` | 4. Returns `4` — largest value in sequence |
▸ Show answer & explanation
Answer: A
`divmod(7,2)` returns the tuple `(3, 1)` (quotient, remainder); `abs(-5.7)` returns `5.7`; `len("Patience")` returns `8` (8 characters); `max([1,2,3,4])` returns `4`. All four match correctly only in option A. ---
Q6. A student writes the following import statement and function call: ```python from math import sqrt, ceil value = ceil(624.7) print(sqrt(value)) ``` What will be printed?
▸ Show answer & explanation
Answer: B
`ceil(624.7)` returns `625` (the smallest integer not less than 624.7). `sqrt(625)` returns `25.0`. When `from math import sqrt, ceil` is used, both functions can be called directly without the `math.` prefix, so option D is incorrect. ---
Q7. Output of the following: ```python def add(a, b=5): return a + b print(add(3)) print(add(3, 7)) ```
▸ Show answer & explanation
Answer: A
`add(3)` uses default b=5 → 3+5=8; `add(3,7)` overrides b → 3+7=10. ---
Q8. Which import statement allows the call `sqrt(16)` to work directly without a prefix?
▸ Show answer & explanation
Answer: C
`from math import sqrt` brings `sqrt` into the current namespace so it can be called without `math.` prefix. ---
Q9. A function that has no `return` statement returns:
▸ Show answer & explanation
Answer: C
Python void functions implicitly return `None`. ---
Q10. What is `divmod(17, 5)`?
▸ Show answer & explanation
Answer: A
`divmod(a,b)` returns `(a//b, a%b)`. Here 17//5=3, 17%5=2. ---
Q11. Which keyword is used inside a function to modify a global variable?
▸ Show answer & explanation
Answer: C
`global` makes a global variable assignable inside a function. `nonlocal` is for nested functions (outside the NCERT syllabus here). ---
Q12. Output of: ```python def f(x, y): return x, y, x + y print(f(2, 3)) ```
▸ Show answer & explanation
Answer: B
Multiple return values pack into a tuple `(2, 3, 5)`. ---
Q13. Which of the following is INVALID as the first line of a function?
▸ Show answer & explanation
Answer: B
Default parameters must be trailing. A non-default after a default is a SyntaxError. ---
Q14. Assertion (A): `math.floor(4.8)` returns 4 while `math.ceil(4.2)` returns 5. Reason (R): floor rounds down to the nearest integer, ceil rounds up to the nearest integer.
▸ Show answer & explanation
Answer: A
floor → greatest integer ≤ x; ceil → smallest integer ≥ x. ---
Q15. The `random.randint(1, 6)` call returns:
▸ Show answer & explanation
Answer: C
`random.randint(a, b)` returns an integer in [a, b] — inclusive on both ends, unlike `randrange`.
📊 Previous-Year Questions
Practise with real CUET Computer Science previous-year papers — every question solved, with the correct answer and a step-by-step explanation.
View solved CUET PYQ papers →Ready to drill Computer Science?
Unlock all MCQs, chapter tests, mocks & PYQs for ₹199/year.
Get UniDrill Pro