1st PUC Computer Science Chapter 7 Functions Notes | Class 11
Complete Short Notes & Exam Preparation Guide
Based on the NCERT Class XI Computer Science textbook chapter.
Exam-focused explanation • Python programs • diagrams • tables • questions
Chapter Overview
verakworld.comAs programs become complex, the number of statements increases and the program may become bulky and difficult to manage. The chapter introduces functions as a way of dividing a program into manageable parts. Functions help achieve modularity and reusability.
Introduction
Functions
User Defined Functions
Scope of a Variable
Python Standard Library
Table of Contents
verakworld.com7.1 Introduction
verakworld.comThe textbook introduces functions through the example of a company that manufactures tents. The tent has a cylindrical part with a conical top. To determine the selling price, the program needs to:
- Accept the height, radius and slant height.
- Calculate the area of canvas required.
- Calculate the cost of the canvas.
- Calculate the net payable amount including 18% tax.
Original Program Idea Without Functions
verakworld.comThe textbook first demonstrates the complete calculation in one continuous program. The important calculations are:
# Calculate conical and cylindrical canvas areas csa_conical = 3.14 * r * l csa_cylindrical = 2 * 3.14 * r * h canvas_area = csa_conical + csa_cylindrical total_cost = unit_price * canvas_area tax = 0.18 * total_cost net_price = total_cost + tax
7.2 Functions
verakworld.comAfter defining a function, it can be called repeatedly from different parts of a program. A function can also be called from another function. Required values can be supplied through parameters.
Function-based approach
verakworld.comdef cylindrical_area(h, r):
return 2 * 3.14 * r * h
def conical_area(l, r):
return 3.14 * r * l
def post_tax_price(cost):
tax = 0.18 * cost
return cost + tax
csa_cyl = cylindrical_area(h, r)
csa_con = conical_area(l, r)
canvas_area = csa_cyl + csa_con
total_cost = unit_price * canvas_area
net_price = post_tax_price(total_cost)
7.2.1 Advantages of Functions
verakworld.com1. Readability
verakworld.comLong programs become better organised and easier to understand.
2. Reduced Code Length
verakworld.comThe same code does not need to be written repeatedly. This also helps debugging.
3. Reusability
verakworld.comA function can be called from another function or another program.
4. Team Work
verakworld.comWork can be divided among team members and completed in parallel.
7.3 User Defined Functions
verakworld.comPython already provides many functions through its standard library. In addition to these, programmers can create their own functions.
7.3.1 Creating User Defined Function
verakworld.comA user defined function definition begins with def.
def function_name([parameters]):
statements
Important Rules
verakworld.comdefis used to begin a function definition.- Parameters enclosed in brackets are optional.
- A function may have parameters or may have no parameters.
- A function may return a value or may not return a value.
- The function header ends with a colon
:. - The function name should be unique and follow identifier naming rules.
- Statements belonging to the function must be properly indented.
- Statements outside the function indentation are not considered part of the function.
Function Definition and Function Call
verakworld.comdef add_numbers():
first = int(input("Enter first number: "))
second = int(input("Enter second number: "))
total = first + second
print("The sum is", total)
add_numbers()
add_numbers()
7.3.2 Arguments and Parameters
verakworld.comdef sum_n(n):
total = 0
for i in range(1, n + 1):
total = total + i
print("Sum =", total)
num = int(input("Enter n: "))
sum_n(num)
Identity of Argument and Parameter
verakworld.comThe chapter demonstrates that before an increment operation, the argument and parameter can refer to the same value. After assigning a new value to the parameter, its identity changes.
def increase_value(num):
print("Before:", num, id(num))
num = num + 5
print("After:", num, id(num))
number = int(input("Enter a number: "))
print("Argument id:", id(number))
increase_value(number)
List as an Argument
verakworld.comdef calculate_mean(values):
total = 0
count = 0
for value in values:
total = total + value
count = count + 1
mean = total / count
print("The calculated mean is:", mean)
myList = [1.3, 2.4, 3.5, 6.9]
calculate_mean(myList)
Factorial Using an Argument
verakworld.comdef factorial_value(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: "))
factorial_value(num)
String as Parameters
verakworld.comArguments passed to a function need not always be numeric. String values can also be passed as arguments. The chapter demonstrates joining first name and last name to form a full name.
def full_name(first, last):
name = first + " " + last
print("Hello", name)
first = input("Enter first name: ")
last = input("Enter last name: ")
full_name(first, last)
+ operator is used to concatenate strings.
Default Parameter
verakworld.comdef mixed_fraction(num, deno=1):
remainder = num % deno
if remainder != 0:
quotient = int(num / deno)
print("Mixed fraction =", quotient, "(", remainder, "/", deno, ")")
else:
print("The fraction evaluates to a whole number")
For example, if the function is called as mixed_fraction(9),
the parameter num receives 9 and deno uses its default value 1.
If a denominator is supplied, the supplied value replaces the default.
Important Rules for Default Parameters
verakworld.com- Arguments should correspond to parameters in the same order.
- An argument may also be an expression.
- Default parameters must be trailing parameters.
- If a parameter has a default value, parameters to its right must also have default values.
| Function Header | Status |
|---|---|
def mixedFraction(num, deno=1): |
Valid |
def mixedFraction(num=2, deno=1): |
Valid |
def calcInterest(principal=1000, rate, time=5): |
Incorrect because a non-default parameter occurs after a default parameter. |
def calcInterest(rate, principal=1000, time=5): |
Correct arrangement. |
7.3.3 Functions Returning Value
verakworld.comNone.
A function may or may not return a value. Functions that perform calculations and only display results without returning a value are described in the chapter as void functions.
Function with Return Value
verakworld.comdef calculate_power(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 = calculate_power(base, expo)
print(base, "raised to the power", expo, "is", answer)
Four Function Forms
verakworld.com| Type | Argument | Return Value |
|---|---|---|
| 1 | No argument | No return value |
| 2 | No argument | With return value(s) |
| 3 | With argument(s) | No return value |
| 4 | With argument(s) | With return value(s) |
Returning Multiple Values
verakworld.comA function can return multiple values through a tuple. The chapter demonstrates returning the area and perimeter of a rectangle.
def rectangle_values(length, breadth):
area = length * breadth
perimeter = 2 * (length + breadth)
return (area, perimeter)
l = float(input("Enter length: "))
b = float(input("Enter breadth: "))
area, perimeter = rectangle_values(l, b)
print("Area is:", area)
print("Perimeter is:", perimeter)
7.3.4 Flow of Execution
verakworld.comThe Python interpreter starts from the first statement and normally executes statements from top to bottom. However, when it encounters a function definition, the statements inside that function are not executed until the function is called. When a function call is reached, control moves to the called function, executes it, and then returns to the point of the call.
NameError can occur because the function name is not yet defined.
# Correct order
def helloPython():
print("I love Programming")
helloPython()
Order of Execution Illustration
verakworld.comdef Greetings(Name):
print("Hello " + Name)
Greetings("John")
print("Thanks")
Execution order: function definition is processed, then the function call executes the function body, followed by the final print.
def RectangleArea(l,b):
return l*b
l = input("Length: ")
b = input("Breadth: ")
Area = RectangleArea(l,b)
print(Area)
print("thanks")
The input statements execute before the function call; control enters the function when the call is reached and then returns.
7.4 Scope of a Variable
verakworld.comThe chapter describes two scopes:
Global Variable
verakworld.comLocal Variable
verakworld.comExample of Global and Local Variables
verakworld.comnum = 5
def my_function():
local_value = num + 5
print("Global value:", num)
print("Local value:", local_value)
my_function()
print("Global outside:", num)
NameError.
Using the global Keyword
verakworld.com
If a function needs to modify a global variable and use the modified value outside the function,
the keyword global is used before the variable name inside the function.
num = 5
def update_number():
global num
print("Accessing num =", num)
num = 10
print("num reassigned =", num)
update_number()
print("Accessing num outside function =", num)
| Global Variable | Local Variable |
|---|---|
| Defined outside a particular function or block. | Defined inside a function or block. |
| Can be accessed in applicable functions. | Can be accessed only within its scope. |
| Changes can affect functions where it is used. | Exists while the function/block is active. |
7.5 Python Standard Library
verakworld.com7.5.1 Built-in Functions
verakworld.comExamples used in the chapter include input(), int() and print().
fname = input("Enter your name: ")
Here, input() receives an argument and returns a value which is stored in fname.
Categories of Built-in Functions
verakworld.com| Input / Output | Datatype Conversion | Mathematical | Other |
|---|---|---|---|
| input() print() |
bool() chr() dict() float() int() list() ord() set() str() tuple() |
abs() divmod() max() min() pow() sum() |
__import__() len() range() type() |
Common Built-in Functions
verakworld.com| Function / Syntax | Arguments | Returns | Example / Output |
|---|---|---|---|
abs(x) |
Integer or floating-point number | Absolute value of x | abs(4) → 4abs(-5.7) → 5.7 |
divmod(x,y) |
x and y | Tuple containing quotient and remainder | divmod(7,2) → (3,1)divmod(7.5,2) → (3.0,1.5) |
max(sequence)max(x,y,z,...) |
Sequence or two or more values | Largest value | max([1,2,3,4]) → 4max(23,4,56) → 56 |
min(sequence)min(x,y,z,...) |
Sequence or two or more values | Smallest value | min([1,2,3,4]) → 1min(23,4,56) → 4 |
pow(x,y[,z]) |
x, y and optional z | x raised to y; with z, modular result | pow(5,2) → 25.0pow(5,2,4) → 1 |
sum(x[,num]) |
Numeric sequence and optional starting value | Sum of elements; optional value is added | sum([2,4,7,3]) → 16sum([2,4,7,3],3) → 19 |
len(x) |
Sequence or dictionary | Number of elements | len("Patience") → 8len([12,34,98]) → 3 |
7.5.2 Module
verakworld.com
A function is a grouping of instructions, while a module is a grouping of functions.
A module is created as a Python .py file.
Importing a Module
verakworld.comimport modulename
Multiple modules can be imported using the appropriate comma-separated form.
Calling a Module Function
verakworld.commodulename.functionname()
The function name is preceded by the module name and a dot.
Built-in Module: math
verakworld.com
The math module contains different mathematical functions. Many functions in this module return floating-point values.
import math
| Function | Purpose | Example |
|---|---|---|
math.ceil(x) | Ceiling value of x | math.ceil(9.7) → 10 |
math.floor(x) | Floor value of x | math.floor(4.5) → 4 |
math.fabs(x) | Absolute value of x | math.fabs(-6.7) → 6.7 |
math.factorial(x) | Factorial of positive integer x | math.factorial(5) → 120 |
math.fmod(x,y) | x % y with the sign of x | math.fmod(4.9,2.5) |
math.gcd(x,y) | Greatest common divisor | math.gcd(10,2) → 2 |
math.pow(x,y) | x raised to power y | math.pow(3,2) → 9.0 |
math.sqrt(x) | Square root | math.sqrt(144) → 12.0 |
math.sin(x) | Sine of x in radians | math.sin(0) → 0 |
Built-in Module: random
verakworld.com
The random module contains functions used to generate random numbers.
import random
| Function | Arguments | Returns | Example |
|---|---|---|---|
random.random() |
No argument | Random floating-point number from 0.0 to 1.0 | random.random() |
random.randint(x,y) |
x and y integers, x ≤ y | Random integer between x and y | random.randint(3,7) |
random.randrange(y) |
Positive stop value | Random integer between 0 and y according to the function’s range behaviour | random.randrange(5) |
random.randrange(x,y) |
Start and stop values | Random integer in the specified range | random.randrange(2,7) |
Built-in Module: statistics
verakworld.com
The statistics module provides functions for calculating statistics of numeric, real-valued data.
import statistics
| Function | Purpose | Example | Output |
|---|---|---|---|
statistics.mean(x) |
Arithmetic mean | statistics.mean([11,24,32,45,51]) |
32.6 |
statistics.median(x) |
Median / middle value | statistics.median([11,24,32,45,51]) |
32 |
statistics.mode(x) |
Mode / most repeated value | statistics.mode([11,24,11,45,11]) |
11 |
help("module") statement can be used to obtain a list of modules, and help("math") can be used to view information about the math module.
From Statement
verakworld.com
Instead of importing an entire module, the from statement can be used to access only the required function or functions.
from modulename import functionname from modulename import function1, function2
When a function is imported using the from statement, the module name does not need to be written before the function call.
from random import random print(random()) from math import ceil, sqrt value = ceil(624.7) print(sqrt(value))
Composition
verakworld.comfrom math import ceil, sqrt value = ceil(624.7) answer = sqrt(value) print(answer)
The same dependency can also be written as:
sqrt(ceil(624.7))
Other composition examples from the chapter include expressions involving input(), int(), mathematical functions and arithmetic expressions.
Docstrings
verakworld.comUser Defined Module: basic_math
verakworld.com"""
basic_math Module
*****************
This module contains basic arithmetic operations
that can be carried out on numbers
"""
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
Using the Module
verakworld.comimport basic_math print(basic_math.__doc__) a = basic_math.addnum(2,5) print(a) a = basic_math.subnum(2,5) print(a) a = basic_math.multnum(2,5) print(a) a = basic_math.divnum(2,5) print(a) a = basic_math.divnum(2,0)
__doc__ variable stores the docstring of a module. It can be displayed using:
print(<modulename>.__doc__)
Application Example: Traffic Light Functions
verakworld.comThe chapter also demonstrates a program in which one user defined function calls another function. The traffic-light colour is checked and another function returns a value representing the colour.
def traffic_light():
signal = input("Enter the colour of the traffic light: ")
if signal not in ("RED", "YELLOW", "GREEN"):
print("Please enter a valid Traffic Light colour 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.")
def light(colour):
if colour == "RED":
return 0
elif colour == "YELLOW":
return 1
else:
return 2
traffic_light()
print("SPEED THRILLS BUT KILLS")
⚡ Quick Revision
verakworld.comImportant Definitions
verakworld.com- Function
- Modular programming
- User defined function
- Argument
- Parameter
- Default parameter
- Flow of execution
- Scope
- Global variable
- Local variable
- Built-in function
- Module
- Composition
- Docstring
Important Syntax
verakworld.comdef name():
statements
def name(parameter):
statements
return value
import module
module.function()
from module import function
Important Modules
verakworld.commathrandomstatistics
Function Forms
verakworld.com- No argument + no return
- No argument + return
- Argument + no return
- Argument + return
High-Value Exam Points
verakworld.com- Functions provide modularity and reusability.
- A user defined function begins with
def. - Function header ends with a colon.
- Arguments are values passed during a function call.
- Parameters receive the corresponding arguments.
- Default parameters have pre-decided values.
- Default parameters must be trailing parameters.
returntransfers control back to the calling function and can return a value.- Multiple values can be returned using a tuple.
- A function definition should appear before its call in the program.
- Global variables are defined outside a particular function.
- Local variables are defined inside a function or block.
- The
globalkeyword is used when a function needs to modify the global variable. - Built-in functions are ready-made functions available in Python.
- A module is a Python file containing function definitions.
importmakes module functions available.fromcan be used to import only required functions.- Python is case sensitive.
- Only required functions can be imported to save memory.
Important Built-in Functions
verakworld.com| Function | Main Use |
|---|---|
| input() | Accept input |
| print() | Display output |
| int() | Integer conversion |
| float() | Floating-point conversion |
| abs() | Absolute value |
| divmod() | Quotient and remainder |
| max() | Largest value |
| min() | Smallest value |
| pow() | Power |
| sum() | Sum of elements |
| len() | Number of elements |
| range() | Generates range values |
| type() | Identifies data type |
📝 Important Questions & Answers
verakworld.comdefParameter: Variable in the function definition that receives the value.
globalmath, random and statistics.import modulenamemodulename.functionname().Difference Questions
verakworld.com| Argument | Parameter |
|---|---|
| Passed during function call. | Written in function header. |
| Provides the value. | Receives the value. |
| Global Variable | Local Variable |
|---|---|
| Defined outside a function/block. | Defined inside a function/block. |
| Can be accessed in applicable functions. | Accessible only within its scope. |
| Can be modified using the global keyword when required. | Belongs to its local scope. |
| Built-in Function | User Defined Function |
|---|---|
| Already provided by Python. | Created by the programmer. |
| Examples: input(), print(), int(). | Examples created with def. |
| import | from |
|---|---|
| Imports the module. | Imports specified function(s). |
| Function generally called using module name. | Imported function can be called directly. |
Chapter Exercise & Exam Practice
verakworld.comThe following questions are based on the exercise, activity-based questions, suggested lab exercises and case-study section of the uploaded chapter.
Error Identification
verakworld.com- Identify the error in a function definition where the function expects two parameters but only one value is passed.
- Identify the problem when a function uses a function name that has not been imported.
- Identify the error caused by trying to modify a variable inside a function without correctly handling its global scope.
- Identify the error in a function header where a non-default parameter follows a default parameter.
- Identify the error in an invalid assignment involving a function call and returned value.
Conceptual Practice
verakworld.com- How is
math.ceil(89.7)different frommath.floor(89.7)? - Which function is suitable for generating random numbers between 1 and 5:
random()orrandint()? Give the reason. - Differentiate between built-in
pow()andmath.pow()with an example. - Show with an example how a Python function can return multiple values.
- Differentiate between argument and parameter with an example.
- Differentiate between global and local variables with an example.
- Does a function always return a value? Explain.
Activity-Based / Programming Practice
verakworld.com- Create a login function that accepts user ID and password and handles limited wrong attempts.
- Create a discount program using a user defined function based on shopping amount and membership conditions.
- Create a learning program using functions for simple words and single-digit addition.
- Create a program to generate the Fibonacci sequence using functions.
- Create a menu-driven calculator using functions for arithmetic operations and selected mathematical functions.
Suggested Lab Exercises
verakworld.com- Write a function to check divisibility of a number by 7.
- Write a function that accepts name and gender and prefixes an appropriate title.
- Write a function to calculate the determinant of a quadratic equation using
b² - 4acand classify it according to the sign of the determinant. - Use the random module to automate a lucky draw from token IDs.
- Write a function to calculate compound interest using the given formula and parameters.
- Write a function that accepts two numbers, swaps them when required, and returns them.
- Create functions for area, perimeter or surface area of shapes such as square, rectangle, triangle, circle and cylinder and use them through a module.
- Create a five-question GK quiz with randomly displayed questions and functions for scoring and remarks.
Case Study Practice
verakworld.com- Convert the functionality of earlier chapter programs into user defined functions.
- Add a function to check short attendance by calculating attendance percentage and returning an appropriate value according to the chapter’s stated condition.
Final Exam Checklist
verakworld.comMust Know
verakworld.com- Function definition
- Function call
- Arguments and parameters
- Default parameters
- Return statement
- Multiple return values
Must Understand
verakworld.com- Flow of execution
- Global vs local scope
- global keyword
- Built-in functions
- Modules
- import vs from
Must Practise
verakworld.com- Function with arguments
- Function with return
- Returning tuple
- Default parameter
- math/random/statistics
- User-defined module
📚 Chapter 7 — Functions
verakworld.comFunctions make programs more organised, reusable and easier to manage. For examination preparation, focus especially on definitions, syntax, arguments and parameters, default parameters, return values, flow of execution, scope, built-in functions, modules and the import/from statements.
Quick Revision + Important Questions
verakworld.com© VerakWorld | Educational Notes
verakworld.com