SlideShare a Scribd company logo
FUNCTIONS
Function Introduction
A function is a subprogram that acts on data and often returns a value
OR
A function is a programming block of codes which is used
1. to perform a single, related task.
2. It only runs when it is called.
3. We can pass data/value, known as parameters, into a function.
4. A function can return data as a result.
Advantages of Using Functions:
1.Program development made easy and fast : Work can be divided among
project members thus implementation can be completed fast.
2. Program testing becomes easy
3. Code sharing becomes possible
4.Code re-usability increases
5. Increases program readability
6.Function facilitates procedural abstraction : Once a function is written,
it serves as a black box. All that a programmer would have to know to invoke a
function would be to know its name, and the parameters that it expects
7.Functions facilitate the factoring of code : A function can be called in
other function and so on…
• Built –in functions (function using Libraries)
• Functions defined in the modules(function using Libraries)
• User defined functions
Types of Functions
Built-in functions
Pre-defined functions that are always available
for use.
e.g.
print() ,len() ,input() ,ord() ,hex() ,type(), int() etc
String functions:
Method Description
isalnum() Returns True if all characters in the string are alphanumeric
isalpha() Returns True if all characters in the string are in the alphabet
isdecimal() Returns True if all characters in the string are decimals
isdigit() Returns True if all characters in the string are digits
islower() Returns True if all characters in the string are lower case
isnumeric() Returns True if all characters in the string are numeric
isspace() Returns True if all characters in the string are whitespaces
istitle() Returns True if the string follows the rules of a title
isupper() Returns True if all characters in the string are upper case
lower() Converts a string into lower case
lstrip() Returns a left trim version of the string
partition() Returns a tuple where the string is parted into three parts
Functions using libraries(System defined function or Built- in Functions)
Syntax:
stringname.functionname()
e.g.
a.isupper()
String functions:
Method Description Syntax
capitalize() Converts the first character to upper case str.capitalize()
center() string padded with specified fillchar. str.center(width,[fillchar])
#Width means length of the string
count() Returns the number of times a specified value
occurs in a string
str.count(substring,[start], [end])
endswith() Returns true if the string ends with the
specified value
str.endswith(substring,[start],[end])
format() Formats specified values in a string print("Hello {}, your rollno {}.".format(“abc", 23))
print("Hello {name}, your rollno {rn}.“
.format(name=“abc", rn=23))
find()
Searches the string for a specified value and
returns the position(index) of where it was
found
str.find(sub,[start],[end] )
index()
Searches the string for a specified value and
returns the position of where it was found
str.index(sub,[start],[end] )
The only difference is that find() method returns -1 if the substring is not found, whereas index() throws an exception.
Functions using libraries(System defined function or Built- in Functions)
String functions:
Method Description
replace()
Returns a string where a specified value is replaced with a
specified value
split() Splits the string at the specified separator, and returns a list
splitlines() Splits the string at line breaks and returns a list
startswith() Returns true if the string starts with the specified value
swapcase() Swaps cases, lower case becomes upper case and vice versa
title() Converts the first character of each word to upper case
upper() Converts a string into upper case
zfill() Fills the string with a specified number of 0 values at the beginning
Functions using libraries(System defined function or Built- in Functions)
Functions defined in modules
Pre-defined functions that are in particular
modules and can only be used when
corresponding module is imported.
e.g.
import math
sin(), cos(),abs(),floor() etc
Modules
Modules
• is a part of a program
• used for dividing up the program into smaller, more easily
understood, reusable parts.
A module is a file containing
1. Python definitions and statements.
2. Module can define functions, classes and variables.
3. A module can also include runnable code.
4. Grouping related code into a module makes the code easier to
understand and use.
Functions using libraries/ Functions defined in Modules
Mathematical functions:
Mathematical functions are available under math module.To use
mathematical functions under this module, we have to import the
module using import math.
For e.g.
To use sqrt() function we have to write statements like given below.
import math
r=math.sqrt(4)
print(r)
OUTPUT :
2.0
Functions available in Python Math Module
Functions using libraries(Functions defined in Modules)
User defined functions
These are defined by the programmer according
to his/her requirements /needs.
Creating a Function (user defined)
A function is defined using the def keyword in
python.
def <function_name>([arguments/parameters]):
[“”” function’s docstring “””]
<statement>
[statement]
[statement]
:
:
Function block/ definition/ working of the function
def fun():
print("Hello")
print(“world”)
e.g.
Syntax: Name of the function
colon at the end means it requires a block
def
means
function
definition
is starting
arguments/parameters-means values given to function
def cals(a):
b=2*a
print(b)
Few terms : Defining functions
• Function header- first line of the function that begins with the
keyword def and end with the (:) colon. It specifies the name of the
function and its parameters
• Parameters-values that are listed within the parentheses of a
function header
• Indentation- blank space in the beginning of a statement within a
block. All statements within the block have same indentation.
Calling a Function(user defined)
Syntax:
def Function_name(arguments/parameters):
statements
#program start here.program code
print("hello before calling a function")
fun(3) #function calling.now function codes will be executed
print("hello after calling a function")
def fun(a):
print(“hello”,a)
Function definition
4 Parts To Create User Defined Functions
•Function definition
•Arguments(those variables which
are use in function calling)
•Parameters(those variables which
are use in function definition)
•Function Calling
Flow of execution in function Calling
• 1 def fun(a,b):
• 2 c=a+b
• 3 print(c)
• 4 x=2
• 5 y=4
• 6 fun(x,y)
1-4-5-6-1-2-3
void functions- those functions which are not
returning values to the calling function
Flow of execution in function Calling
• 1 def fun(a,b):
• 2 c=a+b
• 3 return c
• 4 x=int(input())
• 5 y= int(input())
• 6 z=fun(x,y)
• 7 print(z)
1-4-5-6-1-2-3-6-7
Non void functions- those functions which are
returning values to the calling function
Flow of execution in function Calling
1.def fun(a,b):
2. c=a+b
3. print(c)
4. return
5.x=2
6.y=4
7.z=fun(x,y)
8.print(z)
1-5-6-7-1-2-3-4-8
Void functions- those functions which are not
returning values to the calling function.
We may use return but it will return none value to the
function call
Void functions and Non void functions
def fun(a,b):
c=a+b
print(c)
return
x=2
y=4
z=fun(x,y)
print(z)
We may use return but it will
return none value to the
function call
def fun(a,b):
return a+b, a, 5
x=2
y=4
z,w,q=fun(x,y)
print(z,w,q)
Output
6
None
Output
6 2 5
Value return can be literal,variable ,
expression
Arguments/Parameters
def fun(a,b):
c=a+b
print(c)
x=2
y=4
fun(x,y) #variables
fun(5,6) #literals
fun(x+3,y+6) #expressions
Arguments- passed values in function call.
It can be of three types
1. Literals
2. Variables
3. Expressions
Arguments
Arguments/Parameters
def fun(a,b): #parameters
c=a+b
print(c)
x=2
y=4
fun(x,y)
Parametes- received values in function
definition.
It should be of variable types.
Returning Multiple Values from Functions
def fun(a,b):
return a+b,a-b
x=2
y=4
z=fun(x,y)
print(z)
1. Received values as tuple
2. Unpack received values as tuple
def fun(a,b):
return a+b,a-b
x=2
y=4
d,z=fun(x,y)
print(d,z)
def fun(x,y): #Parameters- variables used in function definition - should be of variable type here x and y are parameters
z=x+y
return z, z**3 ,5 #function can return values in the form of variable, expression, literal
#function calling
a=int(input("enter no1")) #1 a=4
b=int(input("enter no2")) #2 b=5function calling
q=fun(a,b) #variable type arguments (values which are used in function calling)
print(q)
t=fun(3,5) #literal type arguments here 3 and 5 are literal type arguments
print(t)
z=fun(a+3,b+4) #expression type arguments
print(z)
‘’’
Output
enter no1 5
enter no2 6
(11, 1331, 5)
(8, 512, 5)
(18, 5832, 5)
‘’’
Here output is in the form of tuples
becoz function is returning multiple
values and we r storing them in single
variable
Returning Values from Functions
four possible combinations as functions
def fun():
a=2
b=3
print(a,b)
fun()
1. Void functions without arguments
2. Void functions with arguments
def fun(a,b):
print(a+b)
x=2
y=3
fun(x,y)
Returning Values from Functions
four possible combinations as functions
def fun():
a=2
b=3
return(a,b)
c=fun()
print(c)
3. Non Void functions without arguments
4. Non Void functions with arguments
def fun(a,b):
return(a+b)
x=2
y=3
c=fun(x,y)
print(c)
Types of Arguments
def fun(a,b):
c=a+b
print(c)
x=10
y=3
fun(x,y)
fun(x,y,z) #wrong no of arguments passed
1. Positional parameters(Required Arguments) - these arguments
must be provided for all parameters
Types of Arguments
def fun(a,b,c=3):
d=a+b+c
print(d)
x=10
y=3
fun(x,y) #here c parameter value is 3
z=5
fun(x,y,z) #here it will be take parameter c value as 5
2. Default Arguments- if right parameter have default value then left parameters can
also have default value. this argument can be skipped at the time of function calling
Types of Arguments
def fun(a,b,c):
print(a,b,c)
a=1
b=3
c=5
fun(b,c,a)
3. Keyword Arguments(Named Arguments)- We can write arguments in any
order but we must give values according to their name
Output
3 5 1
def fun(a,b,c):
print(a,b,c)
fun(b=3,c=4,a=2)
Output
2 3 4
Scope of Variables
Scope means –to which extent a code or data would be known or accessed.
There are three types of variables with the view of scope.
1. Global Scope- Name declared in main program . It is usable inside the whole
program.
def fun(a,b):
s = a+b
print(s)
X=int(input(“enter no1”))
Y=int(input(“enter no2”))
fun(X,Y)
#here X and Y are global variable
def fun(a):
s = a+Y
retrun(s)
X=10
Y=20
Z=fun(X,Y)
Print(Z)
#here X and Y are global variable
Scope of Variables
Scope means –to which extent a code or data would be known or accessed.
1. Local Scope- Name declared in function body. It is usable within the function.
def fun():
A=10
B=20
return(A+B)
C=fun()
print(C)
print(A)
#here A and B are local variables and C is
global varibale
Variable’s Scope in function
.
1. Non local variable – accessible in nesting of functions,using nonlocal keyword.
def fun1():
x = 100
def fun2():
nonlocal x #change it to global or remove this declaration
x = 200
print("Before calling fun2: " + str(x))
print("Calling fun2 now:")
fun2()
print("After calling fun2: " + str(x))
x=50
fun1()
print("x in main: " + str(x))
OUTPUT:
Before calling fun2: 100
Calling fun2 now:
After calling fun2: 200
x in main: 50
Variable’s Scope in function
There are three types of variables with the view of scope.
1. Local variable – accessible only inside the functional block where it is declared.
2. Global variable – variable which is accessible among whole program using
global keyword.
3. Non local variable – accessible in nesting of functions,using nonlocal keyword.
Local variable program:
def fun():
s = "I love India!" #local variable
print(s)
s = "I love World!"
fun()
print(s)
Output:
I love India!
I love World!
Global variable program:
def fun():
global s #accessing/making global variable for fun()
print(s)
s = "I love India!“ #changing global variable’s value
print(s)
s = "I love world!"
fun()
print(s)
Output:
I love world!
I love India!
I love India!
Name Resolution
.
Resolving Scope of a name: LEGB Rule
1. Local
2. Enclosed
3. Global
4. Built in
.
def fun1(x,y):
s=x+y
print(num1)
return s
num1=100
num2=200
sm=fun1(num1,num2)
print(sm)
.
Variable in global scope not in local scope
CASE 1
Name Resolution
.
Resolving Scope of a name: LEGB Rule
1. Local
2. Enclosed
3. Global
4. Built in
.
def fun():
print(“hello”,n)
fun()
#
Output:
Name error: name ‘n’ is
not defined
.
Variable neither in in local scope nor in global scope
CASE 2
Name Resolution
.
Resolving Scope of a name: LEGB Rule
1. Local
2. Enclosed
3. Global
4. Built in
.
def fun():
a=10
print(a)
a=5
print(a)
fun()
print(a)
# output
5
10
5
.
Variable name in local scope as well as in global scope
CASE 3
Name Resolution
.
Resolving Scope of a name: LEGB Rule
1. Local
2. Enclosed
3. Global
4. Built in
.
def fun():
global a
a=10
print(a)
a=5
print(a)
fun()
print(a)
# output
5
10
10
.
Using global variable inside local scope
This case is discouraged in
good programming
CASE 4
Function
Parameters / Arguments
These are specified after the function name, inside the parentheses. Multiple
parameters are separated by comma.The following example has a function with
two parameters x and y. When the function is called, we pass two values, which
is used inside the function to sum up the values and store in z and then return
the result(z):
def sum(x,y): #x, y are formal arguments
z=x+y
return z #return the result
x,y=4,5
r=sum(x,y) #x, y are actual arguments
print(r)
Note :- 1. Function Prototype is declaration of function with name
,argument and return type.
2. A formal parameter, i.e. a parameter, is in the function definition. An
actual parameter, i.e. an argument, is in a function call.
Function Arguments
Functions can be called using following types of formal arguments −
• Required arguments - arguments passed to a function in correct positional order
• Keyword arguments - the caller identifies the arguments by the parameter name
• Default arguments - that assumes a default value if a value is not provided to argu.
#Required arguments/Positional arguments
def square(x):
z=x*x
return z
print(square(3)
#In above function square() we have to definitely need to
pass some value
#Keyword arguments
def fun( name, age ):
print (name,age)
return;
fun( age=15, name="mohak" )
# value 15 and mohak is being passed to
relevant argument based on keyword used for them.
#Default arguments
def sum(x=3,y=4):
z=x+y
return z
r=sum() #default value of x and y is being used when it is not passed
print(r)
r=sum(x=4)
print(r)
r=sum(y=45)
print(r)
Mutable/Immutable properties of data w/r function
Everything in Python is an object,and every objects in Python can be
either mutable or immutable.
Since everything in Python is an Object, every variable holds an object
instance. When an object is initiated, it is assigned a unique object id. Its
type is defined at runtime and once set can never change, however its
state can be changed if it is mutable.
Means a mutable object can be changed after it is created, and an
immutable object can’t.
Mutable objects: list, dict, set, byte array
Immutable objects: int, float, complex, string, tuple, frozen set ,bytes
Passing Immutable type values to a function
e.g.
def fun(a):
print(a)
a=a+2
print a
n=3
print(n)
fun(n)
print(n)
Output
3
3
5
3
Passed value of n remains unchanged because it is immutable
Passing mutable type value to a function
e.g.
def fun(a):
print(a)
a[0]=1
print (a)
n=[3,5,6]
print(n)
fun(n)
print(n)
Output
3,5,6
3,5,6
1,5,6
1,5,6
Value changed in function change the value in main program(because list
change values at same address and only single value is changing)
CASE-1
Passing mutable type value to a function
e.g.
def fun(a):
print(a)
f=[7,8]
a=f
print (a)
n=[3,5,6]
print(n)
fun(n)
print(n)
Output
3,5,6
3,5,6
7,8
3,5,6
Value changed in function did not change for main program(because a is
assigned a whole new list not a change of single values for whole
program
CASE-2
Pass Mutable type values to a function
Arrays are popular in most programming languages like: Java, C/C++, JavaScript and
so on. However, in Python, they are not that common. When people talk about Python
arrays, more often than not, they are talking about Python lists. Array of numeric
values are supported in Python by the array module.
e.g.
def dosomething( thelist ):
for element in thelist:
print (element)
dosomething( ['1','2','3'] )
alist = ['red','green','blue']
dosomething( alist )
OUTPUT:
1
2
3
red
green
Blue
Note:- List is mutable datatype that’s why it treat as pass by reference.It is
already explained in topic Mutable/immutable properties of data objects w/r
function
Mutable/immutable properties of data objects w/r function
How objects are passed to Functions
#Pass by reference
def updateList(list1):
print(id(list1))
list1 += [10]
print(id(list1))
n = [50, 60]
print(id(n))
updateList(n)
print(n)
print(id(n))
OUTPUT
34122928
34122928
34122928
[50, 60, 10]
34122928
#In above function list1 an object is being passed
and its contents are changing because it ismutable
that’s why it is behaving like pass by reference
#Pass by value
def updateNumber(n):
print(id(n))
n += 10
print(id(n))
b = 5
print(id(b))
updateNumber(b)
print(b)
print(id(b))
OUTPUT
1691040064
1691040064
1691040224
5
1691040064
#In above function value of variable b is not
being changed because it is immutable that’s
why it is behaving like pass by value

More Related Content

PDF
FUNCTIONS IN PYTHON, CLASS 12 COMPUTER SCIENCE
Venugopalavarma Raja
 
PDF
Python revision tour II
Mr. Vikram Singh Slathia
 
PDF
Revised Data Structure- STACK in Python XII CS.pdf
MohammadImran709594
 
PPTX
Chapter 02 functions -class xii
Praveen M Jigajinni
 
PPTX
Chapter 16 Dictionaries
Praveen M Jigajinni
 
PPTX
11 Unit 1 Problem Solving Techniques
Praveen M Jigajinni
 
PPTX
Python-Functions.pptx
Karudaiyar Ganapathy
 
PDF
Chapter8 my sql revision tour
KV(AFS) Utarlai, Barmer (Rajasthan)
 
FUNCTIONS IN PYTHON, CLASS 12 COMPUTER SCIENCE
Venugopalavarma Raja
 
Python revision tour II
Mr. Vikram Singh Slathia
 
Revised Data Structure- STACK in Python XII CS.pdf
MohammadImran709594
 
Chapter 02 functions -class xii
Praveen M Jigajinni
 
Chapter 16 Dictionaries
Praveen M Jigajinni
 
11 Unit 1 Problem Solving Techniques
Praveen M Jigajinni
 
Python-Functions.pptx
Karudaiyar Ganapathy
 
Chapter8 my sql revision tour
KV(AFS) Utarlai, Barmer (Rajasthan)
 

What's hot (20)

PDF
Python revision tour i
Mr. Vikram Singh Slathia
 
PDF
Recursion CBSE Class 12
chinthala Vijaya Kumar
 
PPTX
Chapter 08 data file handling
Praveen M Jigajinni
 
PPTX
classes and objects in C++
HalaiHansaika
 
PPTX
Function in C program
Nurul Zakiah Zamri Tan
 
PPTX
Functions in c language
tanmaymodi4
 
PPT
Memory allocation in c
Prabhu Govind
 
PPT
Function overloading(c++)
Ritika Sharma
 
PPTX
Function in c language(defination and declaration)
VC Infotech
 
PPTX
UNIT 10. Files and file handling in C
Ashim Lamichhane
 
PPTX
Pointers in c++
Vineeta Garg
 
PPSX
Modules and packages in python
TMARAGATHAM
 
PPTX
Python- Regular expression
Megha V
 
PPTX
Function C programming
Appili Vamsi Krishna
 
PPTX
File in C language
Manash Kumar Mondal
 
PPTX
introduction to python
Jincy Nelson
 
PPTX
Hashing in datastructure
rajshreemuthiah
 
PPTX
C functions
University of Potsdam
 
PPT
Data structures using c
Prof. Dr. K. Adisesha
 
PPTX
Presentation on Function in C Programming
Shuvongkor Barman
 
Python revision tour i
Mr. Vikram Singh Slathia
 
Recursion CBSE Class 12
chinthala Vijaya Kumar
 
Chapter 08 data file handling
Praveen M Jigajinni
 
classes and objects in C++
HalaiHansaika
 
Function in C program
Nurul Zakiah Zamri Tan
 
Functions in c language
tanmaymodi4
 
Memory allocation in c
Prabhu Govind
 
Function overloading(c++)
Ritika Sharma
 
Function in c language(defination and declaration)
VC Infotech
 
UNIT 10. Files and file handling in C
Ashim Lamichhane
 
Pointers in c++
Vineeta Garg
 
Modules and packages in python
TMARAGATHAM
 
Python- Regular expression
Megha V
 
Function C programming
Appili Vamsi Krishna
 
File in C language
Manash Kumar Mondal
 
introduction to python
Jincy Nelson
 
Hashing in datastructure
rajshreemuthiah
 
Data structures using c
Prof. Dr. K. Adisesha
 
Presentation on Function in C Programming
Shuvongkor Barman
 
Ad

Similar to Chapter Functions for grade 12 computer Science (20)

PDF
Functions-.pdf
arvdexamsection
 
DOCX
Functions.docx
VandanaGoyal21
 
PDF
2-functions.pptx_20240619_085610_0000.pdf
amiyaratan18
 
PDF
Functions2.pdf
prasnt1
 
PPTX
Python Details Functions Description.pptx
2442230910
 
PPTX
Python_Functions_Modules_ User define Functions-
VidhyaB10
 
PDF
ESIT135 Problem Solving Using Python Notes of Unit-2 and Unit-3
prasadmutkule1
 
PPTX
Python for Data Science function third module ppt.pptx
bmit1
 
PPTX
cbse class 12 Python Functions2 for class 12 .pptx
tcsonline1222
 
PPTX
functions.pptx
KavithaChekuri3
 
PPTX
Functions in python
colorsof
 
PPTX
function_xii-BY APARNA DENDRE (1).pdf.pptx
g84017903
 
PPTX
Python functions PYTHON FUNCTIONS1234567
AnjaneyuluKunchala1
 
PPTX
UNIT-02-pythonfunctions python function using detehdjsjehhdjejdhdjdjdjddjdhdhhd
tony8553004135
 
PPTX
Functions and Modules.pptx
Ashwini Raut
 
PPTX
Python Lecture 4
Inzamam Baig
 
PPTX
2_3 Functions 5d.pptx2_3 Functions 5d.pptx
usha raj
 
PDF
Dive into Python Functions Fundamental Concepts.pdf
SudhanshiBakre1
 
PPTX
Functions_new.pptx
Yagna15
 
PPTX
FUNCTIONINPYTHON.pptx
SheetalMavi2
 
Functions-.pdf
arvdexamsection
 
Functions.docx
VandanaGoyal21
 
2-functions.pptx_20240619_085610_0000.pdf
amiyaratan18
 
Functions2.pdf
prasnt1
 
Python Details Functions Description.pptx
2442230910
 
Python_Functions_Modules_ User define Functions-
VidhyaB10
 
ESIT135 Problem Solving Using Python Notes of Unit-2 and Unit-3
prasadmutkule1
 
Python for Data Science function third module ppt.pptx
bmit1
 
cbse class 12 Python Functions2 for class 12 .pptx
tcsonline1222
 
functions.pptx
KavithaChekuri3
 
Functions in python
colorsof
 
function_xii-BY APARNA DENDRE (1).pdf.pptx
g84017903
 
Python functions PYTHON FUNCTIONS1234567
AnjaneyuluKunchala1
 
UNIT-02-pythonfunctions python function using detehdjsjehhdjejdhdjdjdjddjdhdhhd
tony8553004135
 
Functions and Modules.pptx
Ashwini Raut
 
Python Lecture 4
Inzamam Baig
 
2_3 Functions 5d.pptx2_3 Functions 5d.pptx
usha raj
 
Dive into Python Functions Fundamental Concepts.pdf
SudhanshiBakre1
 
Functions_new.pptx
Yagna15
 
FUNCTIONINPYTHON.pptx
SheetalMavi2
 
Ad

Recently uploaded (20)

PPTX
Understanding operators in c language.pptx
auteharshil95
 
PPTX
Software Engineering BSC DS UNIT 1 .pptx
Dr. Pallawi Bulakh
 
PDF
PG-BPSDMP 2 TAHUN 2025PG-BPSDMP 2 TAHUN 2025.pdf
AshifaRamadhani
 
PPTX
TEF & EA Bsc Nursing 5th sem.....BBBpptx
AneetaSharma15
 
PDF
Origin of periodic table-Mendeleev’s Periodic-Modern Periodic table
Mithil Fal Desai
 
PPTX
IMMUNIZATION PROGRAMME pptx
AneetaSharma15
 
PPTX
An introduction to Dialogue writing.pptx
drsiddhantnagine
 
PPTX
Odoo 18 Sales_ Managing Quotation Validity
Celine George
 
PPTX
An introduction to Prepositions for beginners.pptx
drsiddhantnagine
 
PDF
Landforms and landscapes data surprise preview
jpinnuck
 
PPTX
ACUTE NASOPHARYNGITIS. pptx
AneetaSharma15
 
PDF
Arihant Class 10 All in One Maths full pdf
sajal kumar
 
DOCX
UPPER GASTRO INTESTINAL DISORDER.docx
BANDITA PATRA
 
PPTX
vedic maths in python:unleasing ancient wisdom with modern code
mistrymuskan14
 
PPTX
Open Quiz Monsoon Mind Game Prelims.pptx
Sourav Kr Podder
 
PDF
Module 3: Health Systems Tutorial Slides S2 2025
Jonathan Hallett
 
PPTX
Information Texts_Infographic on Forgetting Curve.pptx
Tata Sevilla
 
PDF
Phylum Arthropoda: Characteristics and Classification, Entomology Lecture
Miraj Khan
 
PDF
What is CFA?? Complete Guide to the Chartered Financial Analyst Program
sp4989653
 
PPTX
Presentation on Janskhiya sthirata kosh.
Ms Usha Vadhel
 
Understanding operators in c language.pptx
auteharshil95
 
Software Engineering BSC DS UNIT 1 .pptx
Dr. Pallawi Bulakh
 
PG-BPSDMP 2 TAHUN 2025PG-BPSDMP 2 TAHUN 2025.pdf
AshifaRamadhani
 
TEF & EA Bsc Nursing 5th sem.....BBBpptx
AneetaSharma15
 
Origin of periodic table-Mendeleev’s Periodic-Modern Periodic table
Mithil Fal Desai
 
IMMUNIZATION PROGRAMME pptx
AneetaSharma15
 
An introduction to Dialogue writing.pptx
drsiddhantnagine
 
Odoo 18 Sales_ Managing Quotation Validity
Celine George
 
An introduction to Prepositions for beginners.pptx
drsiddhantnagine
 
Landforms and landscapes data surprise preview
jpinnuck
 
ACUTE NASOPHARYNGITIS. pptx
AneetaSharma15
 
Arihant Class 10 All in One Maths full pdf
sajal kumar
 
UPPER GASTRO INTESTINAL DISORDER.docx
BANDITA PATRA
 
vedic maths in python:unleasing ancient wisdom with modern code
mistrymuskan14
 
Open Quiz Monsoon Mind Game Prelims.pptx
Sourav Kr Podder
 
Module 3: Health Systems Tutorial Slides S2 2025
Jonathan Hallett
 
Information Texts_Infographic on Forgetting Curve.pptx
Tata Sevilla
 
Phylum Arthropoda: Characteristics and Classification, Entomology Lecture
Miraj Khan
 
What is CFA?? Complete Guide to the Chartered Financial Analyst Program
sp4989653
 
Presentation on Janskhiya sthirata kosh.
Ms Usha Vadhel
 

Chapter Functions for grade 12 computer Science

  • 2. Function Introduction A function is a subprogram that acts on data and often returns a value OR A function is a programming block of codes which is used 1. to perform a single, related task. 2. It only runs when it is called. 3. We can pass data/value, known as parameters, into a function. 4. A function can return data as a result.
  • 3. Advantages of Using Functions: 1.Program development made easy and fast : Work can be divided among project members thus implementation can be completed fast. 2. Program testing becomes easy 3. Code sharing becomes possible 4.Code re-usability increases 5. Increases program readability 6.Function facilitates procedural abstraction : Once a function is written, it serves as a black box. All that a programmer would have to know to invoke a function would be to know its name, and the parameters that it expects 7.Functions facilitate the factoring of code : A function can be called in other function and so on…
  • 4. • Built –in functions (function using Libraries) • Functions defined in the modules(function using Libraries) • User defined functions Types of Functions
  • 5. Built-in functions Pre-defined functions that are always available for use. e.g. print() ,len() ,input() ,ord() ,hex() ,type(), int() etc
  • 6. String functions: Method Description isalnum() Returns True if all characters in the string are alphanumeric isalpha() Returns True if all characters in the string are in the alphabet isdecimal() Returns True if all characters in the string are decimals isdigit() Returns True if all characters in the string are digits islower() Returns True if all characters in the string are lower case isnumeric() Returns True if all characters in the string are numeric isspace() Returns True if all characters in the string are whitespaces istitle() Returns True if the string follows the rules of a title isupper() Returns True if all characters in the string are upper case lower() Converts a string into lower case lstrip() Returns a left trim version of the string partition() Returns a tuple where the string is parted into three parts Functions using libraries(System defined function or Built- in Functions) Syntax: stringname.functionname() e.g. a.isupper()
  • 7. String functions: Method Description Syntax capitalize() Converts the first character to upper case str.capitalize() center() string padded with specified fillchar. str.center(width,[fillchar]) #Width means length of the string count() Returns the number of times a specified value occurs in a string str.count(substring,[start], [end]) endswith() Returns true if the string ends with the specified value str.endswith(substring,[start],[end]) format() Formats specified values in a string print("Hello {}, your rollno {}.".format(“abc", 23)) print("Hello {name}, your rollno {rn}.“ .format(name=“abc", rn=23)) find() Searches the string for a specified value and returns the position(index) of where it was found str.find(sub,[start],[end] ) index() Searches the string for a specified value and returns the position of where it was found str.index(sub,[start],[end] ) The only difference is that find() method returns -1 if the substring is not found, whereas index() throws an exception. Functions using libraries(System defined function or Built- in Functions)
  • 8. String functions: Method Description replace() Returns a string where a specified value is replaced with a specified value split() Splits the string at the specified separator, and returns a list splitlines() Splits the string at line breaks and returns a list startswith() Returns true if the string starts with the specified value swapcase() Swaps cases, lower case becomes upper case and vice versa title() Converts the first character of each word to upper case upper() Converts a string into upper case zfill() Fills the string with a specified number of 0 values at the beginning Functions using libraries(System defined function or Built- in Functions)
  • 9. Functions defined in modules Pre-defined functions that are in particular modules and can only be used when corresponding module is imported. e.g. import math sin(), cos(),abs(),floor() etc
  • 10. Modules Modules • is a part of a program • used for dividing up the program into smaller, more easily understood, reusable parts. A module is a file containing 1. Python definitions and statements. 2. Module can define functions, classes and variables. 3. A module can also include runnable code. 4. Grouping related code into a module makes the code easier to understand and use.
  • 11. Functions using libraries/ Functions defined in Modules Mathematical functions: Mathematical functions are available under math module.To use mathematical functions under this module, we have to import the module using import math. For e.g. To use sqrt() function we have to write statements like given below. import math r=math.sqrt(4) print(r) OUTPUT : 2.0
  • 12. Functions available in Python Math Module Functions using libraries(Functions defined in Modules)
  • 13. User defined functions These are defined by the programmer according to his/her requirements /needs.
  • 14. Creating a Function (user defined) A function is defined using the def keyword in python. def <function_name>([arguments/parameters]): [“”” function’s docstring “””] <statement> [statement] [statement] : : Function block/ definition/ working of the function def fun(): print("Hello") print(“world”) e.g. Syntax: Name of the function colon at the end means it requires a block def means function definition is starting arguments/parameters-means values given to function def cals(a): b=2*a print(b)
  • 15. Few terms : Defining functions • Function header- first line of the function that begins with the keyword def and end with the (:) colon. It specifies the name of the function and its parameters • Parameters-values that are listed within the parentheses of a function header • Indentation- blank space in the beginning of a statement within a block. All statements within the block have same indentation.
  • 16. Calling a Function(user defined) Syntax: def Function_name(arguments/parameters): statements #program start here.program code print("hello before calling a function") fun(3) #function calling.now function codes will be executed print("hello after calling a function") def fun(a): print(“hello”,a) Function definition
  • 17. 4 Parts To Create User Defined Functions •Function definition •Arguments(those variables which are use in function calling) •Parameters(those variables which are use in function definition) •Function Calling
  • 18. Flow of execution in function Calling • 1 def fun(a,b): • 2 c=a+b • 3 print(c) • 4 x=2 • 5 y=4 • 6 fun(x,y) 1-4-5-6-1-2-3 void functions- those functions which are not returning values to the calling function
  • 19. Flow of execution in function Calling • 1 def fun(a,b): • 2 c=a+b • 3 return c • 4 x=int(input()) • 5 y= int(input()) • 6 z=fun(x,y) • 7 print(z) 1-4-5-6-1-2-3-6-7 Non void functions- those functions which are returning values to the calling function
  • 20. Flow of execution in function Calling 1.def fun(a,b): 2. c=a+b 3. print(c) 4. return 5.x=2 6.y=4 7.z=fun(x,y) 8.print(z) 1-5-6-7-1-2-3-4-8 Void functions- those functions which are not returning values to the calling function. We may use return but it will return none value to the function call
  • 21. Void functions and Non void functions def fun(a,b): c=a+b print(c) return x=2 y=4 z=fun(x,y) print(z) We may use return but it will return none value to the function call def fun(a,b): return a+b, a, 5 x=2 y=4 z,w,q=fun(x,y) print(z,w,q) Output 6 None Output 6 2 5 Value return can be literal,variable , expression
  • 22. Arguments/Parameters def fun(a,b): c=a+b print(c) x=2 y=4 fun(x,y) #variables fun(5,6) #literals fun(x+3,y+6) #expressions Arguments- passed values in function call. It can be of three types 1. Literals 2. Variables 3. Expressions Arguments
  • 23. Arguments/Parameters def fun(a,b): #parameters c=a+b print(c) x=2 y=4 fun(x,y) Parametes- received values in function definition. It should be of variable types.
  • 24. Returning Multiple Values from Functions def fun(a,b): return a+b,a-b x=2 y=4 z=fun(x,y) print(z) 1. Received values as tuple 2. Unpack received values as tuple def fun(a,b): return a+b,a-b x=2 y=4 d,z=fun(x,y) print(d,z)
  • 25. def fun(x,y): #Parameters- variables used in function definition - should be of variable type here x and y are parameters z=x+y return z, z**3 ,5 #function can return values in the form of variable, expression, literal #function calling a=int(input("enter no1")) #1 a=4 b=int(input("enter no2")) #2 b=5function calling q=fun(a,b) #variable type arguments (values which are used in function calling) print(q) t=fun(3,5) #literal type arguments here 3 and 5 are literal type arguments print(t) z=fun(a+3,b+4) #expression type arguments print(z) ‘’’ Output enter no1 5 enter no2 6 (11, 1331, 5) (8, 512, 5) (18, 5832, 5) ‘’’ Here output is in the form of tuples becoz function is returning multiple values and we r storing them in single variable
  • 26. Returning Values from Functions four possible combinations as functions def fun(): a=2 b=3 print(a,b) fun() 1. Void functions without arguments 2. Void functions with arguments def fun(a,b): print(a+b) x=2 y=3 fun(x,y)
  • 27. Returning Values from Functions four possible combinations as functions def fun(): a=2 b=3 return(a,b) c=fun() print(c) 3. Non Void functions without arguments 4. Non Void functions with arguments def fun(a,b): return(a+b) x=2 y=3 c=fun(x,y) print(c)
  • 28. Types of Arguments def fun(a,b): c=a+b print(c) x=10 y=3 fun(x,y) fun(x,y,z) #wrong no of arguments passed 1. Positional parameters(Required Arguments) - these arguments must be provided for all parameters
  • 29. Types of Arguments def fun(a,b,c=3): d=a+b+c print(d) x=10 y=3 fun(x,y) #here c parameter value is 3 z=5 fun(x,y,z) #here it will be take parameter c value as 5 2. Default Arguments- if right parameter have default value then left parameters can also have default value. this argument can be skipped at the time of function calling
  • 30. Types of Arguments def fun(a,b,c): print(a,b,c) a=1 b=3 c=5 fun(b,c,a) 3. Keyword Arguments(Named Arguments)- We can write arguments in any order but we must give values according to their name Output 3 5 1 def fun(a,b,c): print(a,b,c) fun(b=3,c=4,a=2) Output 2 3 4
  • 31. Scope of Variables Scope means –to which extent a code or data would be known or accessed. There are three types of variables with the view of scope. 1. Global Scope- Name declared in main program . It is usable inside the whole program. def fun(a,b): s = a+b print(s) X=int(input(“enter no1”)) Y=int(input(“enter no2”)) fun(X,Y) #here X and Y are global variable def fun(a): s = a+Y retrun(s) X=10 Y=20 Z=fun(X,Y) Print(Z) #here X and Y are global variable
  • 32. Scope of Variables Scope means –to which extent a code or data would be known or accessed. 1. Local Scope- Name declared in function body. It is usable within the function. def fun(): A=10 B=20 return(A+B) C=fun() print(C) print(A) #here A and B are local variables and C is global varibale
  • 33. Variable’s Scope in function . 1. Non local variable – accessible in nesting of functions,using nonlocal keyword. def fun1(): x = 100 def fun2(): nonlocal x #change it to global or remove this declaration x = 200 print("Before calling fun2: " + str(x)) print("Calling fun2 now:") fun2() print("After calling fun2: " + str(x)) x=50 fun1() print("x in main: " + str(x)) OUTPUT: Before calling fun2: 100 Calling fun2 now: After calling fun2: 200 x in main: 50
  • 34. Variable’s Scope in function There are three types of variables with the view of scope. 1. Local variable – accessible only inside the functional block where it is declared. 2. Global variable – variable which is accessible among whole program using global keyword. 3. Non local variable – accessible in nesting of functions,using nonlocal keyword. Local variable program: def fun(): s = "I love India!" #local variable print(s) s = "I love World!" fun() print(s) Output: I love India! I love World! Global variable program: def fun(): global s #accessing/making global variable for fun() print(s) s = "I love India!“ #changing global variable’s value print(s) s = "I love world!" fun() print(s) Output: I love world! I love India! I love India!
  • 35. Name Resolution . Resolving Scope of a name: LEGB Rule 1. Local 2. Enclosed 3. Global 4. Built in . def fun1(x,y): s=x+y print(num1) return s num1=100 num2=200 sm=fun1(num1,num2) print(sm) . Variable in global scope not in local scope CASE 1
  • 36. Name Resolution . Resolving Scope of a name: LEGB Rule 1. Local 2. Enclosed 3. Global 4. Built in . def fun(): print(“hello”,n) fun() # Output: Name error: name ‘n’ is not defined . Variable neither in in local scope nor in global scope CASE 2
  • 37. Name Resolution . Resolving Scope of a name: LEGB Rule 1. Local 2. Enclosed 3. Global 4. Built in . def fun(): a=10 print(a) a=5 print(a) fun() print(a) # output 5 10 5 . Variable name in local scope as well as in global scope CASE 3
  • 38. Name Resolution . Resolving Scope of a name: LEGB Rule 1. Local 2. Enclosed 3. Global 4. Built in . def fun(): global a a=10 print(a) a=5 print(a) fun() print(a) # output 5 10 10 . Using global variable inside local scope This case is discouraged in good programming CASE 4
  • 39. Function Parameters / Arguments These are specified after the function name, inside the parentheses. Multiple parameters are separated by comma.The following example has a function with two parameters x and y. When the function is called, we pass two values, which is used inside the function to sum up the values and store in z and then return the result(z): def sum(x,y): #x, y are formal arguments z=x+y return z #return the result x,y=4,5 r=sum(x,y) #x, y are actual arguments print(r) Note :- 1. Function Prototype is declaration of function with name ,argument and return type. 2. A formal parameter, i.e. a parameter, is in the function definition. An actual parameter, i.e. an argument, is in a function call.
  • 40. Function Arguments Functions can be called using following types of formal arguments − • Required arguments - arguments passed to a function in correct positional order • Keyword arguments - the caller identifies the arguments by the parameter name • Default arguments - that assumes a default value if a value is not provided to argu. #Required arguments/Positional arguments def square(x): z=x*x return z print(square(3) #In above function square() we have to definitely need to pass some value #Keyword arguments def fun( name, age ): print (name,age) return; fun( age=15, name="mohak" ) # value 15 and mohak is being passed to relevant argument based on keyword used for them. #Default arguments def sum(x=3,y=4): z=x+y return z r=sum() #default value of x and y is being used when it is not passed print(r) r=sum(x=4) print(r) r=sum(y=45) print(r)
  • 41. Mutable/Immutable properties of data w/r function Everything in Python is an object,and every objects in Python can be either mutable or immutable. Since everything in Python is an Object, every variable holds an object instance. When an object is initiated, it is assigned a unique object id. Its type is defined at runtime and once set can never change, however its state can be changed if it is mutable. Means a mutable object can be changed after it is created, and an immutable object can’t. Mutable objects: list, dict, set, byte array Immutable objects: int, float, complex, string, tuple, frozen set ,bytes
  • 42. Passing Immutable type values to a function e.g. def fun(a): print(a) a=a+2 print a n=3 print(n) fun(n) print(n) Output 3 3 5 3 Passed value of n remains unchanged because it is immutable
  • 43. Passing mutable type value to a function e.g. def fun(a): print(a) a[0]=1 print (a) n=[3,5,6] print(n) fun(n) print(n) Output 3,5,6 3,5,6 1,5,6 1,5,6 Value changed in function change the value in main program(because list change values at same address and only single value is changing) CASE-1
  • 44. Passing mutable type value to a function e.g. def fun(a): print(a) f=[7,8] a=f print (a) n=[3,5,6] print(n) fun(n) print(n) Output 3,5,6 3,5,6 7,8 3,5,6 Value changed in function did not change for main program(because a is assigned a whole new list not a change of single values for whole program CASE-2
  • 45. Pass Mutable type values to a function Arrays are popular in most programming languages like: Java, C/C++, JavaScript and so on. However, in Python, they are not that common. When people talk about Python arrays, more often than not, they are talking about Python lists. Array of numeric values are supported in Python by the array module. e.g. def dosomething( thelist ): for element in thelist: print (element) dosomething( ['1','2','3'] ) alist = ['red','green','blue'] dosomething( alist ) OUTPUT: 1 2 3 red green Blue Note:- List is mutable datatype that’s why it treat as pass by reference.It is already explained in topic Mutable/immutable properties of data objects w/r function
  • 46. Mutable/immutable properties of data objects w/r function How objects are passed to Functions #Pass by reference def updateList(list1): print(id(list1)) list1 += [10] print(id(list1)) n = [50, 60] print(id(n)) updateList(n) print(n) print(id(n)) OUTPUT 34122928 34122928 34122928 [50, 60, 10] 34122928 #In above function list1 an object is being passed and its contents are changing because it ismutable that’s why it is behaving like pass by reference #Pass by value def updateNumber(n): print(id(n)) n += 10 print(id(n)) b = 5 print(id(b)) updateNumber(b) print(b) print(id(b)) OUTPUT 1691040064 1691040064 1691040224 5 1691040064 #In above function value of variable b is not being changed because it is immutable that’s why it is behaving like pass by value