CHAPTER PDF
Complete curriculum textbook chapter document for reading and offline study.
NOTES
Complete conceptual breakdown, formulas, diagrams, and memory aids.
Chapter 7: Functions
Complete, structured notes with definitions, syntax, explanations, Python programs, sample outputs, standard-library reference tables and chapter exercises.
How to use these notes
These notes follow the sequence and terminology of the uploaded NCERT Class XI Computer Science Chapter 7, Functions (Reprint 2026–27). Examples are explained step by step. The chapter's core topics, textbook program themes, summary, notes, practice and lab exercises are included.
7.1 Introduction
As a program becomes more complex, its number of statements increases. A long program can become bulky, difficult to read, test, debug and maintain.
The chapter introduces a tent-manufacturing example. A tent has a cylindrical lower part and a conical top. To calculate its selling price, a program must:
- Accept the cylindrical height, radius and conical slant height.
- Calculate the canvas area.
- Calculate the canvas cost.
- Add 18% tax and calculate the net payable amount.
Formulas used in the tent example
- Curved surface area of cone = π × r × l
- Curved surface area of cylinder = 2 × π × r × h
- Total canvas area = conical area + cylindrical area
- Canvas cost = area × cost per square metre
- Tax = 0.18 × canvas cost
- Net payable = canvas cost + tax
Program 7-1: Without functions
print("Enter values for the cylindrical part of the tent in meters")
h = float(input("Enter height: "))
r = float(input("Enter radius: "))
l = float(input("Enter slant height of conical part: "))
csa_conical = 3.14 * r * l
csa_cylindrical = 2 * 3.14 * r * h
canvas_area = csa_conical + csa_cylindrical
print("Area of canvas =", canvas_area, "m^2")
unit_price = float(input("Enter cost of 1 m^2 canvas: "))
total_cost = unit_price * canvas_area
tax = 0.18 * total_cost
net_price = total_cost + tax
print("Total cost =", total_cost)
print("Net amount payable =", net_price)
This program performs all tasks in one continuous sequence. If the same calculation is needed elsewhere, its statements may have to be copied.
Modular programming
Modular programming is the process of dividing a computer program into separate, independent blocks of code or sub-problems, each with a name and a specific functionality. For the tent program, separate blocks can calculate the cylindrical area, conical area and post-tax price.
7.2 Functions
A function is a named group of instructions that performs a specific task when it is invoked (called). Once defined, it can be called repeatedly from different places in a program. A function can also be called from another function.
Function definition vs function call
Creates the function and specifies the instructions it will execute.
def greet():
print("Hello")Requests Python to execute the function.
greet()Program 7-2: Tent calculation using functions
def cyl(h, r):
area_cyl = 2 * 3.14 * r * h
return area_cyl
def con(l, r):
area_con = 3.14 * r * l
return area_con
def post_tax_price(cost):
tax = 0.18 * cost
net_price = cost + tax
return net_price
h = float(input("Height: "))
r = float(input("Radius: "))
csa_cyl = cyl(h, r)
l = float(input("Slant height: "))
csa_con = con(l, r)
canvas_area = csa_cyl + csa_con
unit_price = float(input("Cost of 1 m^2 canvas: "))
total_cost = unit_price * canvas_area
print("Area of canvas =", canvas_area)
print("Total cost before tax =", total_cost)
print("Net amount payable =", post_tax_price(total_cost))
How it works: cyl(h,r) calculates the cylinder's curved area; con(l,r) calculates the cone's curved area; post_tax_price(cost) adds 18% tax. The returned values are stored and combined in the main program.
7.2.1 Advantages of Functions
- Improves readability: A long program is organised into meaningful tasks.
- Reduces code length: A repeated task is written once instead of being duplicated.
- Makes debugging easier: Individual functions can be tested separately.
- Promotes reusability: A function can be called multiple times, from another function or reused in another program/module.
- Supports teamwork: Different team members can develop separate functions in parallel.
7.3 User-defined Functions
Python provides ready-made functions in its standard library. A programmer can also create functions according to the needs of a particular problem. A function created by the programmer is called a user-defined function.
7.3.1 Creating a user-defined function
A function definition starts with the keyword def, which is short for define.
General syntax
def function_name([parameter1, parameter2, ...]):
statement(s)
[return value]
defbegins the function definition.function_nameis the identifier used to call the function.- Parameters are optional; a function may have zero or more parameters.
- The colon
:ends the function header. - The indented statements form the function body.
returnis optional. A function may return a value or may simply perform an action.
Program 7-3: Add two numbers (no parameters)
def addnum():
fnum = int(input("Enter first number: "))
snum = int(input("Enter second number: "))
total = fnum + snum
print("The sum of", fnum, "and", snum, "is", total)
addnum()Sample outputEnter first number: 5
Enter second number: 6
The sum of 5 and 6 is 11The function accepts input internally, calculates the sum and prints it. The final line addnum() calls the function.
7.3.2 Arguments and Parameters
An argument is the actual value supplied to a function during a function call. A parameter is the variable in the function header that receives the argument.
def show_square(number): # number is a parameter
print(number * number)
value = 6
show_square(value) # value is the argument
Here, the argument value 6 is received by the parameter number.
Program 7-4: Sum of first n natural numbers
def sum_natural(n): # n is the parameter
total = 0
for i in range(1, n + 1):
total = total + i
print("Sum of first", n, "natural numbers =", total)
num = int(input("Enter n: "))
sum_natural(num) # num is the argumentFor n = 5, the function adds 1 + 2 + 3 + 4 + 5 and displays 15. The textbook program is labelled sumSquares, although it actually adds natural numbers, not their squares; the clearer name above describes the calculation.
Argument and parameter identity: Program 7-5
The textbook uses id() to display the identity of the object referred to by a variable.
def incrValue(num):
print("Parameter value:", num, "id =", id(num))
num = num + 5
print("After increment:", num, "id =", id(num))
number = int(input("Enter a number: "))
print("Argument id:", id(number))
incrValue(number)Initially, the argument and parameter refer to the same integer object, so their displayed identities match. The statement num = num + 5 creates/binds the local name num to the resulting integer object; the identity therefore changes. Exact numeric IDs vary between executions and Python implementations.
Same name for argument and parameter: Program 7-6
def myMean(myList):
total = 0
count = 0
for item in myList:
total = total + item
count = count + 1
mean = total / count
print("The calculated mean is:", mean)
myList = [1.3, 2.4, 3.5, 6.9]
myMean(myList)Output: 3.525 (floating-point display may show a tiny representation difference). The outer variable and parameter have the same spelling but are separate names in different scopes.
Program 7-7: Factorial using a function
The factorial of a non-negative integer n, written n!, is the product n × (n−1) × ... × 2 × 1. By definition, 0! = 1.
def calcFact(num):
fact = 1
for i in range(num, 0, -1):
fact = fact * i
print("Factorial of", num, "is", fact)
num = int(input("Enter the number: "))
calcFact(num)For input 5, the calculation is 5 × 4 × 3 × 2 × 1 = 120.
(A) String as parameters: Program 7-8
def fullname(first, last):
full_name = first + " " + last
print("Hello", full_name)
first = input("Enter first name: ")
last = input("Enter last name: ")
fullname(first, last)Example: first name Gyan, last name Vardhan produces Hello Gyan Vardhan. The + operator concatenates the strings; an explicit space is added between them.
(B) Default Parameters
A default parameter has a preassigned value. If the corresponding argument is omitted from the function call, Python uses the default.
Syntax
def function_name(required_parameter, optional_parameter=default_value):
statements
Program 7-9: Display a mixed fraction
def mixedFraction(num, deno=1):
remainder = num % deno
if remainder != 0:
quotient = num // deno
print("The mixed fraction =", quotient,
"(", remainder, "/", deno, ")")
else:
print("The given fraction evaluates to a whole number")
num = int(input("Enter numerator: "))
deno = int(input("Enter denominator: "))
print("You entered:", num, "/", deno)
if deno == 0:
print("Denominator cannot be zero")
elif num > deno:
mixedFraction(num, deno)
else:
print("It is a proper fraction")For 17/2, quotient = 8 and remainder = 1, so the mixed fraction is 8 1/2. If mixedFraction(9) is called, num becomes 9 and deno uses its default value 1.
Rules for default parameters
- Arguments are matched to parameters in their defined order when positional arguments are used.
- A default parameter can be omitted from the function call.
- Default parameters must be placed after parameters without defaults.
# Correct
def calcInterest(rate, principal=1000, time=5):
pass
# Incorrect: a non-default parameter follows a default parameter
# def calcInterest(principal=1000, rate, time=5):An argument may also be an expression, such as mixedFraction(num + 5, deno + 5); Python evaluates the expression before passing the value.
7.3.3 Functions Returning Value
A function may display a result, return a result, or do both. The return statement sends a value back to the statement that called the function and transfers control back to the caller.
return valuesends a value to the caller.returnwithout an expression returnsNone.- If execution reaches the end of a function without a return statement, Python also returns
None.
A function that performs an action without explicitly returning a useful result is often called a void function in introductory textbooks.
Program 7-10: Calculate base raised to exponent
def calcpow(number, power):
result = 1
for i in range(1, power + 1):
result = result * number
return result
base = int(input("Enter the base: "))
expo = int(input("Enter the exponent: "))
answer = calcpow(base, expo)
print(base, "raised to the power", expo, "is", answer)For base 5 and exponent 4, the function returns 625. The caller stores the returned value in answer.
Four possible function designs
| Parameters | Return value | Example |
|---|---|---|
| No arguments | No value | greet() reads input and prints greeting. |
| No arguments | With value | get_number() reads and returns a number. |
| With arguments | No value | display_sum(a,b) prints the sum. |
| With arguments | With value | add(a,b) returns the sum. |
Returning multiple values using a tuple: Program 7-12
Python can return multiple values from a function. They are packed into a tuple and can be unpacked into separate variables by the caller.
def calcAreaPeri(length, breadth):
area = length * breadth
perimeter = 2 * (length + breadth)
return area, perimeter
l = float(input("Enter length: "))
b = float(input("Enter breadth: "))
area, perimeter = calcAreaPeri(l, b)
print("Area is:", area)
print("Perimeter is:", perimeter)For length 45 and breadth 66, area = 2970 and perimeter = 222.
Program 7-13: Traffic-light simulation
This example demonstrates two functions calling each other. light() maps RED to 0, YELLOW to 1 and GREEN to 2. trafficLight() validates input and displays the appropriate message.
def light(colour):
if colour == "RED":
return 0
elif colour == "YELLOW":
return 1
else:
return 2
def trafficLight():
signal = input("Enter traffic-light colour: ")
if signal not in ("RED", "YELLOW", "GREEN"):
print("Please enter RED, YELLOW or GREEN in capitals")
else:
value = light(signal)
if value == 0:
print("STOP, your life is precious")
elif value == 1:
print("PLEASE GO SLOW")
else:
print("GO! Thank you for being patient")
trafficLight()
print("SPEED THRILLS BUT KILLS")7.3.4 Flow of Execution
Flow of execution is the order in which statements in a program are executed. Normally, Python executes statements from top to bottom. Function definitions are processed when encountered, but their bodies do not run until the function is called.
- Python starts at the first statement.
- When it encounters a function definition, it creates the function; it does not execute the function body at that point.
- When it encounters a function call, control moves to the called function.
- The function statements execute.
- When the function returns or finishes, control resumes after the function call.
Why define a function before calling it?
# Incorrect order
helloPython()
def helloPython():
print("I love Programming")This raises NameError because the name has not yet been defined when Python reaches the call.
# Correct order
def helloPython():
print("I love Programming")
helloPython()
Tracing nested function calls
def Greetings(name): # step 2: enter function definition on call
print("Hello", name) # step 3
Greetings("John") # step 1: call
print("Thanks") # step 4Read a function-based program by following calls, not merely by assuming that every function body runs where it appears in the file.
7.4 Scope of a Variable
The scope of a variable is the part of a program where that variable can be accessed. The chapter discusses global and local scope.
(A) Global variable
A global variable is defined outside a function. It can be accessed inside functions defined in the program, subject to Python's name-resolution rules.
(B) Local variable
A local variable is defined inside a function. It is available within that function's local scope and cannot ordinarily be accessed directly from outside it.
Program 7-14: Accessing global and local variables
num = 5 # global variable
def myFunc1():
y = num + 5 # y is local; num is read globally
print("Global num =", num)
print("Local y =", y)
myFunc1()
print("num outside function =", num)
# print(y) # NameError: y is not defined here
Using the global keyword: Program 7-15
If a function needs to reassign a global variable, use the global keyword to declare that the name refers to the global binding.
num = 5
def myfunc1():
global num
print("Accessing num =", num)
num = 10
print("num reassigned =", num)
myfunc1()
print("Accessing num outside function =", num)Output values are 5, then 10, then 10. The reassignment is visible outside the function because the global name was explicitly declared.
Important scope rules
- A local variable is not available outside its function.
- A function can read a global variable if no local binding with that name takes precedence.
- If a name is assigned inside a function, Python normally treats it as local unless declared
global(ornonlocalin an enclosing function). - A local variable with the same name as a global variable shadows the global name within that function.
- Changes to a mutable global object can be visible outside even without rebinding its name; the
globalkeyword is needed for rebinding the global name.
7.5 Python Standard Library
The Python standard library is a collection of ready-to-use code that saves programmers from repeatedly writing commonly needed functionality. The chapter classifies functions into built-in functions and functions supplied through modules.
Available directly in Python, for example print(), input(), len().
Grouped in modules and generally accessed after importing, for example math.sqrt().
7.5.1 Built-in Functions
Built-in functions are ready-made functions available directly in Python. Their implementation is already provided by the Python interpreter/runtime.
Categories and examples
| Category | Functions listed in the chapter |
|---|---|
| Input/output | input(), print() |
| Datatype conversion | bool(), chr(), dict(), float(), int(), list(), ord(), set(), str(), tuple() |
| Mathematical | abs(), divmod(), max(), min(), pow(), sum() |
| Other | __import__(), len(), range(), type() |
Common built-in functions (Table 7.1)
| Function | Purpose / return | Example and result |
|---|---|---|
abs(x) | Absolute value of a number. | abs(4) → 4abs(-5.7) → 5.7 |
divmod(x,y) | Returns a tuple containing quotient and remainder. | divmod(7,2) → (3, 1)divmod(7.5,2) → (3.0, 1.5) |
max(sequence) or max(a,b,...) | Largest item in a sequence or largest argument. | max([1,2,3,4]) → 4max(23,4,56) → 56 |
min(sequence) or min(a,b,...) | Smallest item in a sequence or smallest argument. | min([1,2,3,4]) → 1min(23,4,56) → 4 |
pow(x,y[,z]) | Returns x raised to y; with z, returns modular power (x**y) % z. | pow(5,2) → 25pow(5,2,4) → 1 |
sum(x[,start]) | Adds numeric items in an iterable; optional start is added to the total. | sum([2,4,7,3]) → 16sum([2,4,7,3],3) → 19 |
len(x) | Number of items in a sequence or mapping. | len("Patience") → 8len([12,34,98]) → 3len((9,45)) → 2 |
How to interpret a built-in function call: In fname = input("Enter your name: "), the function name is input, the prompt string is an argument, and the function returns the text entered by the user. That returned string is assigned to fname.
pow(5,2) shows 25.0, whereas current standard Python returns the integer 25 for integer arguments. The mathematical result is the same; displayed type can depend on argument types and Python version.7.5.2 Modules
A module is a Python file (normally with a .py extension) containing a collection of function definitions, variables and other reusable code. A function groups instructions; a module groups related definitions. Modules help organise large programs and reuse functions across programs.
Importing a module
import module_name
import module_one, module_twoAfter importing, access a function using the module name, a dot and the function name.
module_name.function_name(arguments)
Python is case-sensitive. The standard-library module names used in this chapter are lowercase: math, random and statistics.
Built-in module 1: math
The math module provides mathematical functions. Import it with:
import math
| Function | What it returns | Example |
|---|---|---|
math.ceil(x) | Smallest integer greater than or equal to x (ceiling). | math.ceil(-9.7) → -9math.ceil(9.7) → 10 |
math.floor(x) | Largest integer less than or equal to x (floor). | math.floor(-4.5) → -5math.floor(4.5) → 4 |
math.fabs(x) | Absolute value as a float. | math.fabs(-6.7) → 6.7math.fabs(-4) → 4.0 |
math.factorial(x) | Factorial of a non-negative integer. | math.factorial(5) → 120 |
math.fmod(x,y) | Floating-point remainder, with sign of x. | math.fmod(-4.9,2.5) → -2.4 |
math.gcd(x,y) | Greatest common divisor of integers. | math.gcd(10,2) → 2 |
math.pow(x,y) | x raised to the power y; returns float. | math.pow(3,2) → 9.0 |
math.sqrt(x) | Square root of x (for non-negative real x). | math.sqrt(144) → 12.0math.sqrt(.64) → 0.8 |
math.sin(x) | Sine of x, where x is in radians. | math.sin(0) → 0.0 |
ceil(4.2) is 5; floor(4.2) is 4. For negative values, move toward positive infinity for ceiling and toward negative infinity for floor.Built-in module 2: random
The random module provides functions for generating pseudo-random values. Import it with:
import random
| Function | Purpose | Example |
|---|---|---|
random.random() | Returns a floating-point number greater than or equal to 0.0 and less than 1.0. | random.random() → e.g. 0.6533 |
random.randint(x,y) | Returns an integer from x through y, including both endpoints. | random.randint(3,7) → any integer 3, 4, 5, 6 or 7 |
random.randrange(y) | Returns an integer from 0 up to, but not including, y. | random.randrange(5) → 0 to 4 |
random.randrange(x,y) | Returns an integer from x up to, but not including, y. | random.randrange(2,7) → 2 to 6 |
import random
token = random.randint(1, 600)
print("Lucky draw token:", token)Each run may produce a different value. For reproducible demonstrations, a seed can be set using random.seed(value), though this is an additional Python detail.
Built-in module 3: statistics
The statistics module provides functions for analysing numerical data. Import it with:
import statistics
| Function | Meaning | Example and result |
|---|---|---|
statistics.mean(x) | Arithmetic mean (average). | statistics.mean([11,24,32,45,51]) → 32.6 |
statistics.median(x) | Median (middle value after ordering the data). | statistics.median([11,24,32,45,51]) → 32 |
statistics.mode(x) | Mode (most frequently occurring value). | statistics.mode([11,24,11,45,11]) → 11 |
For the data 11, 24, 32, 45, 51, the mean is (11+24+32+45+51)/5 = 32.6 and the median is 32.
Getting help about modules
help("module") # list information about available modules
help("math") # display help for the math moduleStandard-library modules are installed with Python; the textbook notes that they can be found in Python's Lib folder.
(B) The from statement
Instead of referring to functions through the module name, the from statement imports selected function names directly.
Syntax
from module_name import function_name
from module_name import function_one, function_twoAfter this import, call the selected functions without the module prefix.
from random import random
print(random())
from math import ceil, sqrt
value = ceil(624.7)
print(sqrt(value))The second example first calculates ceil(624.7) = 625, then calculates the square root of 625 = 25.0.
from as loading only the required function(s), which can save memory. In modern Python, imports are cached and module loading has additional implementation details; for this chapter, remember the key syntax and that imported names can be called directly.Composition of functions and expressions
Composition is the use of functions or expressions whose execution depends on the result of another function or expression. The result of one operation becomes the input to another.
a = int(input("First number: "))
print("Square root =", math.sqrt(a))
print(math.floor(a + (b / c)))
print(math.sin(float(h) / float(c)))For example, in sqrt(ceil(624.7)), Python evaluates the inner function ceil() first, then passes its result to sqrt().
from math import ceil, sqrt
answer = sqrt(ceil(624.7))
print(answer) # 25.0Creating your own module: Program 7-16
A programmer can store user-defined functions in a separate .py file and import that file as a module in another program.
Step 1: Create basic_math.py
"""
basic_math Module
This module contains basic arithmetic operations.
"""
def addnum(x, y):
return x + y
def subnum(x, y):
return x - y
def multnum(x, y):
return x * y
def divnum(x, y):
if y == 0:
print("Division by Zero Error")
else:
return x / y
Step 2: Save the file
Save the code with the exact filename basic_math.py. Keep it in the same folder as the program or Python environment from which it will be imported.
Step 3: Import and use the module
import basic_math
print(basic_math.__doc__)
print(basic_math.addnum(2, 5)) # 7
print(basic_math.subnum(2, 5)) # -3
print(basic_math.multnum(2, 5)) # 10
print(basic_math.divnum(2, 5)) # 0.4
basic_math.divnum(2, 0) # Division by Zero Error
Docstrings and __doc__
A docstring (documentation string) is a string literal used to document a module, function or class. It is commonly written as the first statement using triple quotes. The module's documentation string can be accessed through module_name.__doc__. There are two underscores before and after doc.
.py file. The module name is used before the dot when calling one of its functions, e.g. basic_math.addnum(2,5).Chapter Summary
- Functions provide modularity and reusability.
- A function is a named group of instructions executed when it is called.
- Programmers can create user-defined functions with
def. - An argument is passed during a function call; a parameter receives it in the function header.
- Parameters may have default values.
- The
returnstatement sends values back to the caller. - Multiple values can be returned together as a tuple.
- Flow of execution is the order in which statements run.
- Scope determines where a variable can be accessed.
- Global variables are defined outside functions; local variables are defined inside functions.
- The Python standard library contains built-in functions and modules.
- A module is a Python file containing reusable definitions.
- Use
importto import a module andfrom ... import ...to import selected names.
Quick syntax reference
| Task | Syntax |
|---|---|
| Define function | def name(parameters): |
| Call function | name(arguments) |
| Return a value | return expression |
| Default parameter | def name(x, y=10): |
| Global variable assignment in function | global variable_name |
| Import module | import module_name |
| Import selected function | from module_name import function_name |
| Call module function | module_name.function_name() |
| Read module docstring | module_name.__doc__ |
Chapter Exercises – Practice and Understanding
The following exercise prompts are organised from the chapter's exercise section. Use them to test your understanding after studying the notes.
Textbook Exercise (page 170)
- Observe the following programs and identify the errors:
def create(text, freq):followed by a loopfor i in range(1, freq): print(text), but the call iscreate(5). Identify the argument mismatch (and ensure print uses parentheses in Python 3).from math import sqrt, ceil; a function callscos(0)without importing or qualifyingcos. Identify the undefined name.- A global
mynum = 9is incremented usingmynum = mynum + 9inside a function without declaring it global. Explain the local-binding / scope error. def findValue(val1=1.1, val2, val3):places non-default parameters after a default parameter. Correct the header order.greet() = messageattempts to assign to a function call. Rewrite it asmessage = greet().
- How is
math.ceil(89.7)different frommath.floor(89.7)? - To generate random integers between 1 and 5, should
random()orrandint()be used? Justify your answer. - How is built-in
pow()different frommath.pow()? Explain with an example. - Using an example, show how a function in Python can return multiple values.
- Differentiate between (a) argument and parameter, and (b) global and local variable, with examples.
Activity-based questions (pages 171–172)
- Write a function
login(uid, pwd)that accepts user ID and password. Allow three attempts; after three wrong attempts display “account blocked”. The correct credentials specified in the textbook are user IDADMINand passwordSt0rE@1. On success display “login successful”. - Create a festival-discount program for XYZ Store. Shopping amount discounts: 5% for amounts ≥500 and <1000; 8% for ≥1000 and <2000; 10% for ≥2000. Members receive an additional 5% discount. Calculate net payable as shopping amount minus discount.
- Design a play-and-learn program using user-defined functions to help toddlers practise two- and three-letter English words and single-digit addition. Analyse questions appropriate to the age and curriculum.
- Generate the Fibonacci series 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, ... by repeatedly adding the previous two numbers.
- Create a menu-driven calculator using user-defined functions for +, −, ×, ÷,
log10(x),sin(x)andcos(x).
Programming practice based on chapter examples
- Write a function to add two numbers.
- Write a function that accepts n and displays the sum of the first n natural numbers.
- Write a function that calculates the mean of values in a list.
- Write a function that calculates the factorial of a number.
- Write a function that accepts first name and last name and displays the full name.
- Write a function with a default denominator parameter to display an improper fraction as a mixed fraction.
- Write a function that returns a number raised to a given power.
- Write a function that returns both area and perimeter of a rectangle.
- Write a traffic-light simulation using two functions.
- Write a program demonstrating global and local variables.
Notes and Suggested Lab Exercises
Additional practice prompts from the chapter
- Fibonacci sequence: Generate the sequence 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, ... by starting with 1 and 1 and repeatedly adding the previous two numbers.
- Menu-driven calculator: Use user-defined functions to perform basic arithmetic operations (+, −, ×, ÷),
log10(x),sin(x)andcos(x).
Suggested Lab Exercises (all eight)
- Write a program to check divisibility of a number by 7. Pass the number as a parameter to a user-defined function.
- Write a function that accepts a name and gender (M for Male, F for Female) and prefixes Mr. or Ms. accordingly.
- Write a function that accepts coefficients a, b and c of a quadratic equation and calculates the determinant
b² − 4ac. Check whether the determinant is positive, zero or negative and display the appropriate result. - ABC School has allotted unique token IDs from 1 to 600 to parents for a lucky draw. Write a Python program to automate selection of a winner. Hint: use the
randommodule. - Write a function that accepts principal amount, rate, time and number of compounding periods and calculates compound interest using
CI = P × (1 + r/n)^(n×t) − P, where r is the annual rate expressed as a decimal. - Write a function that accepts two numbers. If number 1 is less than number 2, swap them; return the resulting pair. Otherwise return them in the original order.
- Create user-defined functions to calculate area, perimeter or surface area, as applicable, for a square, rectangle, triangle, circle and cylinder. Accept required values as parameters, return calculated values, save the functions in a module, import it and use the appropriate functions.
- Create a GK quiz of five questions displayed randomly. Create
score()to calculate the score andremark(scorevalue)to display the remark according to the table below.
| Marks | Remark |
|---|---|
| 5 | Outstanding |
| 4 | Excellent |
| 3 | Good |
| 2 | Read more to score more |
| 1 | Needs to take interest |
| 0 | General knowledge will always help you. Take it seriously. |
Useful hints for the lab
- Divisibility by 7: use
number % 7 == 0. - Quadratic discriminant:
d = b*b - 4*a*c. - Lucky draw: use
random.randint(1, 600). - Swapping: return
(number2, number1)when the condition is true. - Quiz order: shuffle question indices using
random.shuffle().
Case Study-based Question: SMIS
For the Student Management Information System (SMIS) case study extended from earlier chapters, the chapter asks students to:
- Convert all functionality developed in Chapters 5 and 6 into user-defined functions.
- Add a user-defined function to check whether a student has short attendance.
Short-attendance function requirements
- The function accepts the total number of working days in a month.
- Calculate attendance percentage using: (number of days present ÷ total working days) × 100.
- If attendance is less than 78%, return
1to indicate short attendance. - Otherwise, return
0to indicate attendance is not short.
Illustrative implementation
def check_short_attendance(days_present, working_days):
if working_days <= 0:
raise ValueError("Working days must be greater than zero")
attendance = (days_present / working_days) * 100
if attendance < 78:
return 1
else:
return 0
present = int(input("Days present: "))
working = int(input("Total working days: "))
status = check_short_attendance(present, working)
if status == 1:
print("Short attendance")
else:
print("Attendance is not short")
The chapter also asks learners to peer-review other students' case studies using the documentation tips provided at the end of Chapter 5.
Final Revision Checklist
- Can you write a function definition and call it?
- Can you identify arguments and parameters?
- Can you explain default parameters and their placement rule?
- Can you distinguish printing a result from returning a result?
- Can you return two values and unpack the tuple?
- Can you trace the flow of execution when functions call other functions?
- Can you identify local and global variables and use
globalappropriately? - Can you use the listed built-in functions?
- Can you import and use
math,randomandstatistics? - Can you create and import your own
.pymodule?
TEXTBOOK SOLUTION
Step-by-step solved textbook exercises, derivations, and solutions.
Exercise Solutions Being Updated
Step-by-step verified exercise solutions are currently being uploaded.
IMPORTANT QUESTION
High-yield board questions, previous year questions (PYQs), and model answer keys.
Important Questions Being Compiled
Board blueprint and previous years' exam questions for this chapter will be live soon.