SlideShare a Scribd company logo
Chapter 2 :
Computer Science
Class XII ( As per
CBSE Board)
Functions
Visit : python.mykvs.in for regular updates
New
Syllabus
2019-20
Function Introduction
A function is a programming block of codes which
is used to perform a single, related task. It only
runs when it is called. We can pass data, known
as parameters, into a function. A function can
return data as a result.
We have already used some python built in
functions like print(),etc.But we can also create
our own functions. These functions are
called user-defined functions.
Visit : python.mykvs.in for regular updates
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 : Easy to locate and isolate a faulty function
for further investigation
3.Code sharing becomes possible : A function may be used later by many
other programs this means that a python programmer can use function written by
others, instead of starting over from scratch.
4.Code re-usability increases : A function can be used to keep away from
rewriting the same block of codes which we are going use two or more locations in
a program. This is especially useful if the code involved is long or complicated.
5.Increases program readability : It makes possible top down modular
programming. In this style of programming, the high level logic of the overall
problem is solved first while the details of each lower level functions is addressed
later. The length of the source program can be reduced by using functions at
appropriate places.
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…
Visit : python.mykvs.in for regular updates
Creating & calling a Function(user defined)
A function is defined using the def keyword in
python.E.g. program is given below.
def my_own_function():
print("Hello from a function")
#program start here.program code
print("hello before calling a function")
my_own_function() #function calling.now function codes will be executed
print("hello after calling a function")
Save the above source code in python file and
execute it
Visit : python.mykvs.in for regular updates
#Function block/
definition/creation
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.
Visit : python.mykvs.in for regular updates
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!
Variable’s Scope in function
#Find the output of below program
def fun(x, y): # argument /parameter x and y
global a
a = 10
x,y = y,x
b = 20
b = 30
c = 30
print(a,b,x,y)
a, b, x, y = 1, 2, 3,4
fun(50, 100) #passing value 50 and 100 in parameter x and y of function fun()
print(a, b, x, y)
Visit : python.mykvs.in for regular updates
Variable’s Scope in function
#Find the output of below program
def fun(x, y): # argument /parameter x and y
global a
a = 10
x,y = y,x
b = 20
b = 30
c = 30
print(a,b,x,y)
a, b, x, y = 1, 2, 3,4
fun(50, 100) #passing value 50 and 100 in parameter x and y of function fun()
print(a, b, x, y)
OUTPUT :-
10 30 100 50
10 2 3 4
Visit : python.mykvs.in for regular updates
Variable’s Scope in function
Visit : python.mykvs.in for regular updates
Global variables in nested function
def fun1():
x = 100
def fun2():
global x
x = 200
print("Before calling fun2: " + str(x))
print("Calling fun2 now:")
fun2()
print("After calling fun2: " + str(x))
fun1()
print("x in main: " + str(x))
OUTPUT:
Before calling fun2: 100
Calling fun2 now:
After calling fun2: 100
x in main: 200
Variable’s Scope in function
Visit : python.mykvs.in for regular updates
Non local variable
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
Function
Visit : python.mykvs.in for regular updates
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
Visit : python.mykvs.in for regular updates
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.
• Variable-length arguments – pass multiple values with single argument name.
#Required arguments
def square(x):
z=x*x
return z
r=square()
print(r)
#In above function square() we have to
definitely need to pass some value to
argument x.
#Keyword arguments
def fun( name, age ):
"This prints a passed info into this
function"
print ("Name: ", name)
print ("Age ", age)
return;
# Now you can call printinfo function
fun( age=15, name="mohak" )
# value 15 and mohak is being passed
to relevant argument based on keyword
used for them.
Function
Visit : python.mykvs.in for regular updates
#Default arguments
def sum(x=3,y=4):
z=x+y
return z
r=sum()
print(r)
r=sum(x=4)
print(r)
r=sum(y=45)
print(r)
#default value of x and y is being used
when it is not passed
#Variable length arguments
def sum( *vartuple ):
s=0
for var in vartuple:
s=s+int(var)
return s;
r=sum( 70, 60, 50 )
print(r)
r=sum(4,5)
print(r)
#now the above function sum() can sum
n number of values
Lamda
Visit : python.mykvs.in for regular updates
Python Lambda
A lambda function is a small anonymous function which can take any number of
arguments, but can only have one expression.
E.g.
x = lambda a, b : a * b
print(x(5, 6))
OUTPUT:
30
Mutable/immutable properties of data objects w/r function
Visit : python.mykvs.in for regular updates
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
Mutable/immutable properties of data objects w/r function
Visit : python.mykvs.in for regular updates
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 is mutable
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
Pass arrays to functions
Visit : python.mykvs.in for regular updates
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
Functions using libraries
Visit : python.mykvs.in for regular updates
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 using libraries
Visit : python.mykvs.in for regular updates
Functions available in Python Math Module
Functions using libraries(System defined function)
Visit : python.mykvs.in for regular updates
String functions:
String functions are available in python standard module.These are always
availble to use.
For e.g. capitalize() function Converts the first character of string to upper
case.
s="i love programming"
r=s.capitalize()
print(r)
OUTPUT:
I love programming
Functions using libraries
Visit : python.mykvs.in for regular updates
String functions:
Method Description
capitalize() Converts the first character to upper case
casefold() Converts string into lower case
center() Returns a centered string
count() Returns the number of times a specified value occurs in a string
encode() Returns an encoded version of the string
endswith() Returns true if the string ends with the specified value
find()
Searches the string for a specified value and returns the position
of where it was found
format() Formats specified values in a string
index()
Searches the string for a specified value and returns the position
of where it was found
Functions using libraries
Visit : python.mykvs.in for regular updates
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
isidentifier() Returns True if the string is an identifier
islower() Returns True if all characters in the string are lower case
isnumeric() Returns True if all characters in the string are numeric
isprintable() Returns True if all characters in the string are printable
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
join() Joins the elements of an iterable to the end of the string
ljust() Returns a left justified version of the string
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
Visit : python.mykvs.in for regular updates
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
translate() Returns a translated string
upper() Converts a string into upper case
zfill() Fills the string with a specified number of 0 values at the beginning
Ad

More Related Content

Similar to Functions_19_20.pdf (20)

Functions2.pdf
Functions2.pdfFunctions2.pdf
Functions2.pdf
prasnt1
 
Functions in python
Functions in pythonFunctions in python
Functions in python
colorsof
 
ESIT135 Problem Solving Using Python Notes of Unit-2 and Unit-3
ESIT135 Problem Solving Using Python Notes of Unit-2 and Unit-3ESIT135 Problem Solving Using Python Notes of Unit-2 and Unit-3
ESIT135 Problem Solving Using Python Notes of Unit-2 and Unit-3
prasadmutkule1
 
Unit 2function in python.pptx
Unit 2function in python.pptxUnit 2function in python.pptx
Unit 2function in python.pptx
vishnupriyapm4
 
Unit 2function in python.pptx
Unit 2function in python.pptxUnit 2function in python.pptx
Unit 2function in python.pptx
vishnupriyapm4
 
functionfunctionfunctionfunctionfunction12.pdf
functionfunctionfunctionfunctionfunction12.pdffunctionfunctionfunctionfunctionfunction12.pdf
functionfunctionfunctionfunctionfunction12.pdf
jeevithequeen2025
 
functionfunctionfunctionfunctionfunction12.pdf
functionfunctionfunctionfunctionfunction12.pdffunctionfunctionfunctionfunctionfunction12.pdf
functionfunctionfunctionfunctionfunction12.pdf
jeevithequeen2025
 
Functions in Pythons UDF and Functions Concepts
Functions in Pythons UDF and Functions ConceptsFunctions in Pythons UDF and Functions Concepts
Functions in Pythons UDF and Functions Concepts
nitinaees
 
function.pptx
function.pptxfunction.pptx
function.pptx
SwapnaliGawali5
 
Python Functions.pptx
Python Functions.pptxPython Functions.pptx
Python Functions.pptx
AnuragBharti27
 
Python Functions.pptx
Python Functions.pptxPython Functions.pptx
Python Functions.pptx
AnuragBharti27
 
Functionincprogram
FunctionincprogramFunctionincprogram
Functionincprogram
Sampath Kumar
 
Functions.docx
Functions.docxFunctions.docx
Functions.docx
VandanaGoyal21
 
Python Lecture 4
Python Lecture 4Python Lecture 4
Python Lecture 4
Inzamam Baig
 
Python_Unit_2.pdf
Python_Unit_2.pdfPython_Unit_2.pdf
Python_Unit_2.pdf
alaparthi
 
USER DEFINED FUNCTIONS IN C.pdf
USER DEFINED FUNCTIONS IN C.pdfUSER DEFINED FUNCTIONS IN C.pdf
USER DEFINED FUNCTIONS IN C.pdf
BoomBoomers
 
cp Module4(1)
cp Module4(1)cp Module4(1)
cp Module4(1)
Amarjith C K
 
Decided to go to the 65 and the value of the number
Decided to go to the 65 and the value of the numberDecided to go to the 65 and the value of the number
Decided to go to the 65 and the value of the number
harshoberoi2050
 
functions _
functions                                 _functions                                 _
functions _
SwatiHans10
 
JNTUK python programming python unit 3.pptx
JNTUK python programming python unit 3.pptxJNTUK python programming python unit 3.pptx
JNTUK python programming python unit 3.pptx
Venkateswara Babu Ravipati
 
Functions2.pdf
Functions2.pdfFunctions2.pdf
Functions2.pdf
prasnt1
 
Functions in python
Functions in pythonFunctions in python
Functions in python
colorsof
 
ESIT135 Problem Solving Using Python Notes of Unit-2 and Unit-3
ESIT135 Problem Solving Using Python Notes of Unit-2 and Unit-3ESIT135 Problem Solving Using Python Notes of Unit-2 and Unit-3
ESIT135 Problem Solving Using Python Notes of Unit-2 and Unit-3
prasadmutkule1
 
Unit 2function in python.pptx
Unit 2function in python.pptxUnit 2function in python.pptx
Unit 2function in python.pptx
vishnupriyapm4
 
Unit 2function in python.pptx
Unit 2function in python.pptxUnit 2function in python.pptx
Unit 2function in python.pptx
vishnupriyapm4
 
functionfunctionfunctionfunctionfunction12.pdf
functionfunctionfunctionfunctionfunction12.pdffunctionfunctionfunctionfunctionfunction12.pdf
functionfunctionfunctionfunctionfunction12.pdf
jeevithequeen2025
 
functionfunctionfunctionfunctionfunction12.pdf
functionfunctionfunctionfunctionfunction12.pdffunctionfunctionfunctionfunctionfunction12.pdf
functionfunctionfunctionfunctionfunction12.pdf
jeevithequeen2025
 
Functions in Pythons UDF and Functions Concepts
Functions in Pythons UDF and Functions ConceptsFunctions in Pythons UDF and Functions Concepts
Functions in Pythons UDF and Functions Concepts
nitinaees
 
Python_Unit_2.pdf
Python_Unit_2.pdfPython_Unit_2.pdf
Python_Unit_2.pdf
alaparthi
 
USER DEFINED FUNCTIONS IN C.pdf
USER DEFINED FUNCTIONS IN C.pdfUSER DEFINED FUNCTIONS IN C.pdf
USER DEFINED FUNCTIONS IN C.pdf
BoomBoomers
 
Decided to go to the 65 and the value of the number
Decided to go to the 65 and the value of the numberDecided to go to the 65 and the value of the number
Decided to go to the 65 and the value of the number
harshoberoi2050
 

More from paijitk (13)

Manual eXtreme karaoke music karaoke.pdf
Manual eXtreme karaoke music karaoke.pdfManual eXtreme karaoke music karaoke.pdf
Manual eXtreme karaoke music karaoke.pdf
paijitk
 
การรักษาสิวด้วยสมุนไพรจีน การรักษาด้วยสมุนไพรจีนได้ผลดีและ มีผลข้างเคียงน้อย.pdf
การรักษาสิวด้วยสมุนไพรจีน การรักษาด้วยสมุนไพรจีนได้ผลดีและ มีผลข้างเคียงน้อย.pdfการรักษาสิวด้วยสมุนไพรจีน การรักษาด้วยสมุนไพรจีนได้ผลดีและ มีผลข้างเคียงน้อย.pdf
การรักษาสิวด้วยสมุนไพรจีน การรักษาด้วยสมุนไพรจีนได้ผลดีและ มีผลข้างเคียงน้อย.pdf
paijitk
 
IDIO2020_B3_DataViz_EdoraFNguyenJ_acc.pdf
IDIO2020_B3_DataViz_EdoraFNguyenJ_acc.pdfIDIO2020_B3_DataViz_EdoraFNguyenJ_acc.pdf
IDIO2020_B3_DataViz_EdoraFNguyenJ_acc.pdf
paijitk
 
ลำดับการโพสต์วันปฐมนิเทศ ญาณสาสมาธิ (ออนไ.pdf
ลำดับการโพสต์วันปฐมนิเทศ ญาณสาสมาธิ (ออนไ.pdfลำดับการโพสต์วันปฐมนิเทศ ญาณสาสมาธิ (ออนไ.pdf
ลำดับการโพสต์วันปฐมนิเทศ ญาณสาสมาธิ (ออนไ.pdf
paijitk
 
Chapter_01wht.pdf
Chapter_01wht.pdfChapter_01wht.pdf
Chapter_01wht.pdf
paijitk
 
functions2-200924082810.pdf
functions2-200924082810.pdffunctions2-200924082810.pdf
functions2-200924082810.pdf
paijitk
 
stringsinpython-181122100212.pdf
stringsinpython-181122100212.pdfstringsinpython-181122100212.pdf
stringsinpython-181122100212.pdf
paijitk
 
Python-review1.pdf
Python-review1.pdfPython-review1.pdf
Python-review1.pdf
paijitk
 
03-Data-Exploration.en.th.pptx
03-Data-Exploration.en.th.pptx03-Data-Exploration.en.th.pptx
03-Data-Exploration.en.th.pptx
paijitk
 
02-Lifecycle.en.th.pptx
02-Lifecycle.en.th.pptx02-Lifecycle.en.th.pptx
02-Lifecycle.en.th.pptx
paijitk
 
01. Introduction.en.th.pptx
01. Introduction.en.th.pptx01. Introduction.en.th.pptx
01. Introduction.en.th.pptx
paijitk
 
Lecture_2_Stats.pdf
Lecture_2_Stats.pdfLecture_2_Stats.pdf
Lecture_2_Stats.pdf
paijitk
 
Lecture_1_Intro.pdf
Lecture_1_Intro.pdfLecture_1_Intro.pdf
Lecture_1_Intro.pdf
paijitk
 
Manual eXtreme karaoke music karaoke.pdf
Manual eXtreme karaoke music karaoke.pdfManual eXtreme karaoke music karaoke.pdf
Manual eXtreme karaoke music karaoke.pdf
paijitk
 
การรักษาสิวด้วยสมุนไพรจีน การรักษาด้วยสมุนไพรจีนได้ผลดีและ มีผลข้างเคียงน้อย.pdf
การรักษาสิวด้วยสมุนไพรจีน การรักษาด้วยสมุนไพรจีนได้ผลดีและ มีผลข้างเคียงน้อย.pdfการรักษาสิวด้วยสมุนไพรจีน การรักษาด้วยสมุนไพรจีนได้ผลดีและ มีผลข้างเคียงน้อย.pdf
การรักษาสิวด้วยสมุนไพรจีน การรักษาด้วยสมุนไพรจีนได้ผลดีและ มีผลข้างเคียงน้อย.pdf
paijitk
 
IDIO2020_B3_DataViz_EdoraFNguyenJ_acc.pdf
IDIO2020_B3_DataViz_EdoraFNguyenJ_acc.pdfIDIO2020_B3_DataViz_EdoraFNguyenJ_acc.pdf
IDIO2020_B3_DataViz_EdoraFNguyenJ_acc.pdf
paijitk
 
ลำดับการโพสต์วันปฐมนิเทศ ญาณสาสมาธิ (ออนไ.pdf
ลำดับการโพสต์วันปฐมนิเทศ ญาณสาสมาธิ (ออนไ.pdfลำดับการโพสต์วันปฐมนิเทศ ญาณสาสมาธิ (ออนไ.pdf
ลำดับการโพสต์วันปฐมนิเทศ ญาณสาสมาธิ (ออนไ.pdf
paijitk
 
Chapter_01wht.pdf
Chapter_01wht.pdfChapter_01wht.pdf
Chapter_01wht.pdf
paijitk
 
functions2-200924082810.pdf
functions2-200924082810.pdffunctions2-200924082810.pdf
functions2-200924082810.pdf
paijitk
 
stringsinpython-181122100212.pdf
stringsinpython-181122100212.pdfstringsinpython-181122100212.pdf
stringsinpython-181122100212.pdf
paijitk
 
Python-review1.pdf
Python-review1.pdfPython-review1.pdf
Python-review1.pdf
paijitk
 
03-Data-Exploration.en.th.pptx
03-Data-Exploration.en.th.pptx03-Data-Exploration.en.th.pptx
03-Data-Exploration.en.th.pptx
paijitk
 
02-Lifecycle.en.th.pptx
02-Lifecycle.en.th.pptx02-Lifecycle.en.th.pptx
02-Lifecycle.en.th.pptx
paijitk
 
01. Introduction.en.th.pptx
01. Introduction.en.th.pptx01. Introduction.en.th.pptx
01. Introduction.en.th.pptx
paijitk
 
Lecture_2_Stats.pdf
Lecture_2_Stats.pdfLecture_2_Stats.pdf
Lecture_2_Stats.pdf
paijitk
 
Lecture_1_Intro.pdf
Lecture_1_Intro.pdfLecture_1_Intro.pdf
Lecture_1_Intro.pdf
paijitk
 
Ad

Recently uploaded (20)

Stein, Hunt, Green letter to Congress April 2025
Stein, Hunt, Green letter to Congress April 2025Stein, Hunt, Green letter to Congress April 2025
Stein, Hunt, Green letter to Congress April 2025
Mebane Rash
 
LDMMIA Reiki Master Spring 2025 Mini Updates
LDMMIA Reiki Master Spring 2025 Mini UpdatesLDMMIA Reiki Master Spring 2025 Mini Updates
LDMMIA Reiki Master Spring 2025 Mini Updates
LDM Mia eStudios
 
Biophysics Chapter 3 Methods of Studying Macromolecules.pdf
Biophysics Chapter 3 Methods of Studying Macromolecules.pdfBiophysics Chapter 3 Methods of Studying Macromolecules.pdf
Biophysics Chapter 3 Methods of Studying Macromolecules.pdf
PKLI-Institute of Nursing and Allied Health Sciences Lahore , Pakistan.
 
Multi-currency in odoo accounting and Update exchange rates automatically in ...
Multi-currency in odoo accounting and Update exchange rates automatically in ...Multi-currency in odoo accounting and Update exchange rates automatically in ...
Multi-currency in odoo accounting and Update exchange rates automatically in ...
Celine George
 
Introduction to Vibe Coding and Vibe Engineering
Introduction to Vibe Coding and Vibe EngineeringIntroduction to Vibe Coding and Vibe Engineering
Introduction to Vibe Coding and Vibe Engineering
Damian T. Gordon
 
Political History of Pala dynasty Pala Rulers NEP.pptx
Political History of Pala dynasty Pala Rulers NEP.pptxPolitical History of Pala dynasty Pala Rulers NEP.pptx
Political History of Pala dynasty Pala Rulers NEP.pptx
Arya Mahila P. G. College, Banaras Hindu University, Varanasi, India.
 
How to manage Multiple Warehouses for multiple floors in odoo point of sale
How to manage Multiple Warehouses for multiple floors in odoo point of saleHow to manage Multiple Warehouses for multiple floors in odoo point of sale
How to manage Multiple Warehouses for multiple floors in odoo point of sale
Celine George
 
P-glycoprotein pamphlet: iteration 4 of 4 final
P-glycoprotein pamphlet: iteration 4 of 4 finalP-glycoprotein pamphlet: iteration 4 of 4 final
P-glycoprotein pamphlet: iteration 4 of 4 final
bs22n2s
 
K12 Tableau Tuesday - Algebra Equity and Access in Atlanta Public Schools
K12 Tableau Tuesday  - Algebra Equity and Access in Atlanta Public SchoolsK12 Tableau Tuesday  - Algebra Equity and Access in Atlanta Public Schools
K12 Tableau Tuesday - Algebra Equity and Access in Atlanta Public Schools
dogden2
 
Social Problem-Unemployment .pptx notes for Physiotherapy Students
Social Problem-Unemployment .pptx notes for Physiotherapy StudentsSocial Problem-Unemployment .pptx notes for Physiotherapy Students
Social Problem-Unemployment .pptx notes for Physiotherapy Students
DrNidhiAgarwal
 
Operations Management (Dr. Abdulfatah Salem).pdf
Operations Management (Dr. Abdulfatah Salem).pdfOperations Management (Dr. Abdulfatah Salem).pdf
Operations Management (Dr. Abdulfatah Salem).pdf
Arab Academy for Science, Technology and Maritime Transport
 
Anti-Depressants pharmacology 1slide.pptx
Anti-Depressants pharmacology 1slide.pptxAnti-Depressants pharmacology 1slide.pptx
Anti-Depressants pharmacology 1slide.pptx
Mayuri Chavan
 
Marie Boran Special Collections Librarian Hardiman Library, University of Gal...
Marie Boran Special Collections Librarian Hardiman Library, University of Gal...Marie Boran Special Collections Librarian Hardiman Library, University of Gal...
Marie Boran Special Collections Librarian Hardiman Library, University of Gal...
Library Association of Ireland
 
apa-style-referencing-visual-guide-2025.pdf
apa-style-referencing-visual-guide-2025.pdfapa-style-referencing-visual-guide-2025.pdf
apa-style-referencing-visual-guide-2025.pdf
Ishika Ghosh
 
How to Customize Your Financial Reports & Tax Reports With Odoo 17 Accounting
How to Customize Your Financial Reports & Tax Reports With Odoo 17 AccountingHow to Customize Your Financial Reports & Tax Reports With Odoo 17 Accounting
How to Customize Your Financial Reports & Tax Reports With Odoo 17 Accounting
Celine George
 
New Microsoft PowerPoint Presentation.pptx
New Microsoft PowerPoint Presentation.pptxNew Microsoft PowerPoint Presentation.pptx
New Microsoft PowerPoint Presentation.pptx
milanasargsyan5
 
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - WorksheetCBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
Sritoma Majumder
 
Sinhala_Male_Names.pdf Sinhala_Male_Name
Sinhala_Male_Names.pdf Sinhala_Male_NameSinhala_Male_Names.pdf Sinhala_Male_Name
Sinhala_Male_Names.pdf Sinhala_Male_Name
keshanf79
 
How to Manage Opening & Closing Controls in Odoo 17 POS
How to Manage Opening & Closing Controls in Odoo 17 POSHow to Manage Opening & Closing Controls in Odoo 17 POS
How to Manage Opening & Closing Controls in Odoo 17 POS
Celine George
 
To study the nervous system of insect.pptx
To study the nervous system of insect.pptxTo study the nervous system of insect.pptx
To study the nervous system of insect.pptx
Arshad Shaikh
 
Stein, Hunt, Green letter to Congress April 2025
Stein, Hunt, Green letter to Congress April 2025Stein, Hunt, Green letter to Congress April 2025
Stein, Hunt, Green letter to Congress April 2025
Mebane Rash
 
LDMMIA Reiki Master Spring 2025 Mini Updates
LDMMIA Reiki Master Spring 2025 Mini UpdatesLDMMIA Reiki Master Spring 2025 Mini Updates
LDMMIA Reiki Master Spring 2025 Mini Updates
LDM Mia eStudios
 
Multi-currency in odoo accounting and Update exchange rates automatically in ...
Multi-currency in odoo accounting and Update exchange rates automatically in ...Multi-currency in odoo accounting and Update exchange rates automatically in ...
Multi-currency in odoo accounting and Update exchange rates automatically in ...
Celine George
 
Introduction to Vibe Coding and Vibe Engineering
Introduction to Vibe Coding and Vibe EngineeringIntroduction to Vibe Coding and Vibe Engineering
Introduction to Vibe Coding and Vibe Engineering
Damian T. Gordon
 
How to manage Multiple Warehouses for multiple floors in odoo point of sale
How to manage Multiple Warehouses for multiple floors in odoo point of saleHow to manage Multiple Warehouses for multiple floors in odoo point of sale
How to manage Multiple Warehouses for multiple floors in odoo point of sale
Celine George
 
P-glycoprotein pamphlet: iteration 4 of 4 final
P-glycoprotein pamphlet: iteration 4 of 4 finalP-glycoprotein pamphlet: iteration 4 of 4 final
P-glycoprotein pamphlet: iteration 4 of 4 final
bs22n2s
 
K12 Tableau Tuesday - Algebra Equity and Access in Atlanta Public Schools
K12 Tableau Tuesday  - Algebra Equity and Access in Atlanta Public SchoolsK12 Tableau Tuesday  - Algebra Equity and Access in Atlanta Public Schools
K12 Tableau Tuesday - Algebra Equity and Access in Atlanta Public Schools
dogden2
 
Social Problem-Unemployment .pptx notes for Physiotherapy Students
Social Problem-Unemployment .pptx notes for Physiotherapy StudentsSocial Problem-Unemployment .pptx notes for Physiotherapy Students
Social Problem-Unemployment .pptx notes for Physiotherapy Students
DrNidhiAgarwal
 
Anti-Depressants pharmacology 1slide.pptx
Anti-Depressants pharmacology 1slide.pptxAnti-Depressants pharmacology 1slide.pptx
Anti-Depressants pharmacology 1slide.pptx
Mayuri Chavan
 
Marie Boran Special Collections Librarian Hardiman Library, University of Gal...
Marie Boran Special Collections Librarian Hardiman Library, University of Gal...Marie Boran Special Collections Librarian Hardiman Library, University of Gal...
Marie Boran Special Collections Librarian Hardiman Library, University of Gal...
Library Association of Ireland
 
apa-style-referencing-visual-guide-2025.pdf
apa-style-referencing-visual-guide-2025.pdfapa-style-referencing-visual-guide-2025.pdf
apa-style-referencing-visual-guide-2025.pdf
Ishika Ghosh
 
How to Customize Your Financial Reports & Tax Reports With Odoo 17 Accounting
How to Customize Your Financial Reports & Tax Reports With Odoo 17 AccountingHow to Customize Your Financial Reports & Tax Reports With Odoo 17 Accounting
How to Customize Your Financial Reports & Tax Reports With Odoo 17 Accounting
Celine George
 
New Microsoft PowerPoint Presentation.pptx
New Microsoft PowerPoint Presentation.pptxNew Microsoft PowerPoint Presentation.pptx
New Microsoft PowerPoint Presentation.pptx
milanasargsyan5
 
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - WorksheetCBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
Sritoma Majumder
 
Sinhala_Male_Names.pdf Sinhala_Male_Name
Sinhala_Male_Names.pdf Sinhala_Male_NameSinhala_Male_Names.pdf Sinhala_Male_Name
Sinhala_Male_Names.pdf Sinhala_Male_Name
keshanf79
 
How to Manage Opening & Closing Controls in Odoo 17 POS
How to Manage Opening & Closing Controls in Odoo 17 POSHow to Manage Opening & Closing Controls in Odoo 17 POS
How to Manage Opening & Closing Controls in Odoo 17 POS
Celine George
 
To study the nervous system of insect.pptx
To study the nervous system of insect.pptxTo study the nervous system of insect.pptx
To study the nervous system of insect.pptx
Arshad Shaikh
 
Ad

Functions_19_20.pdf

  • 1. Chapter 2 : Computer Science Class XII ( As per CBSE Board) Functions Visit : python.mykvs.in for regular updates New Syllabus 2019-20
  • 2. Function Introduction A function is a programming block of codes which is used to perform a single, related task. It only runs when it is called. We can pass data, known as parameters, into a function. A function can return data as a result. We have already used some python built in functions like print(),etc.But we can also create our own functions. These functions are called user-defined functions. Visit : python.mykvs.in for regular updates
  • 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 : Easy to locate and isolate a faulty function for further investigation 3.Code sharing becomes possible : A function may be used later by many other programs this means that a python programmer can use function written by others, instead of starting over from scratch. 4.Code re-usability increases : A function can be used to keep away from rewriting the same block of codes which we are going use two or more locations in a program. This is especially useful if the code involved is long or complicated. 5.Increases program readability : It makes possible top down modular programming. In this style of programming, the high level logic of the overall problem is solved first while the details of each lower level functions is addressed later. The length of the source program can be reduced by using functions at appropriate places. 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… Visit : python.mykvs.in for regular updates
  • 4. Creating & calling a Function(user defined) A function is defined using the def keyword in python.E.g. program is given below. def my_own_function(): print("Hello from a function") #program start here.program code print("hello before calling a function") my_own_function() #function calling.now function codes will be executed print("hello after calling a function") Save the above source code in python file and execute it Visit : python.mykvs.in for regular updates #Function block/ definition/creation
  • 5. 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. Visit : python.mykvs.in for regular updates 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!
  • 6. Variable’s Scope in function #Find the output of below program def fun(x, y): # argument /parameter x and y global a a = 10 x,y = y,x b = 20 b = 30 c = 30 print(a,b,x,y) a, b, x, y = 1, 2, 3,4 fun(50, 100) #passing value 50 and 100 in parameter x and y of function fun() print(a, b, x, y) Visit : python.mykvs.in for regular updates
  • 7. Variable’s Scope in function #Find the output of below program def fun(x, y): # argument /parameter x and y global a a = 10 x,y = y,x b = 20 b = 30 c = 30 print(a,b,x,y) a, b, x, y = 1, 2, 3,4 fun(50, 100) #passing value 50 and 100 in parameter x and y of function fun() print(a, b, x, y) OUTPUT :- 10 30 100 50 10 2 3 4 Visit : python.mykvs.in for regular updates
  • 8. Variable’s Scope in function Visit : python.mykvs.in for regular updates Global variables in nested function def fun1(): x = 100 def fun2(): global x x = 200 print("Before calling fun2: " + str(x)) print("Calling fun2 now:") fun2() print("After calling fun2: " + str(x)) fun1() print("x in main: " + str(x)) OUTPUT: Before calling fun2: 100 Calling fun2 now: After calling fun2: 100 x in main: 200
  • 9. Variable’s Scope in function Visit : python.mykvs.in for regular updates Non local variable 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
  • 10. Function Visit : python.mykvs.in for regular updates 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.
  • 11. Function Visit : python.mykvs.in for regular updates 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. • Variable-length arguments – pass multiple values with single argument name. #Required arguments def square(x): z=x*x return z r=square() print(r) #In above function square() we have to definitely need to pass some value to argument x. #Keyword arguments def fun( name, age ): "This prints a passed info into this function" print ("Name: ", name) print ("Age ", age) return; # Now you can call printinfo function fun( age=15, name="mohak" ) # value 15 and mohak is being passed to relevant argument based on keyword used for them.
  • 12. Function Visit : python.mykvs.in for regular updates #Default arguments def sum(x=3,y=4): z=x+y return z r=sum() print(r) r=sum(x=4) print(r) r=sum(y=45) print(r) #default value of x and y is being used when it is not passed #Variable length arguments def sum( *vartuple ): s=0 for var in vartuple: s=s+int(var) return s; r=sum( 70, 60, 50 ) print(r) r=sum(4,5) print(r) #now the above function sum() can sum n number of values
  • 13. Lamda Visit : python.mykvs.in for regular updates Python Lambda A lambda function is a small anonymous function which can take any number of arguments, but can only have one expression. E.g. x = lambda a, b : a * b print(x(5, 6)) OUTPUT: 30
  • 14. Mutable/immutable properties of data objects w/r function Visit : python.mykvs.in for regular updates 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
  • 15. Mutable/immutable properties of data objects w/r function Visit : python.mykvs.in for regular updates 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 is mutable 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
  • 16. Pass arrays to functions Visit : python.mykvs.in for regular updates 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
  • 17. Functions using libraries Visit : python.mykvs.in for regular updates 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
  • 18. Functions using libraries Visit : python.mykvs.in for regular updates Functions available in Python Math Module
  • 19. Functions using libraries(System defined function) Visit : python.mykvs.in for regular updates String functions: String functions are available in python standard module.These are always availble to use. For e.g. capitalize() function Converts the first character of string to upper case. s="i love programming" r=s.capitalize() print(r) OUTPUT: I love programming
  • 20. Functions using libraries Visit : python.mykvs.in for regular updates String functions: Method Description capitalize() Converts the first character to upper case casefold() Converts string into lower case center() Returns a centered string count() Returns the number of times a specified value occurs in a string encode() Returns an encoded version of the string endswith() Returns true if the string ends with the specified value find() Searches the string for a specified value and returns the position of where it was found format() Formats specified values in a string index() Searches the string for a specified value and returns the position of where it was found
  • 21. Functions using libraries Visit : python.mykvs.in for regular updates 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 isidentifier() Returns True if the string is an identifier islower() Returns True if all characters in the string are lower case isnumeric() Returns True if all characters in the string are numeric isprintable() Returns True if all characters in the string are printable 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 join() Joins the elements of an iterable to the end of the string ljust() Returns a left justified version of the string 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
  • 22. Functions using libraries Visit : python.mykvs.in for regular updates 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 translate() Returns a translated string upper() Converts a string into upper case zfill() Fills the string with a specified number of 0 values at the beginning