0% found this document useful (0 votes)
2 views

3_Functions

The document provides an overview of functions in Python, detailing their definition, advantages, types, and how to create and call them. It covers built-in functions, user-defined functions, variable scope, and argument passing, including default and variable-length arguments. Additionally, it discusses the properties of mutable and immutable objects, as well as mathematical and string functions available in Python libraries.

Uploaded by

sspslab9
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

3_Functions

The document provides an overview of functions in Python, detailing their definition, advantages, types, and how to create and call them. It covers built-in functions, user-defined functions, variable scope, and argument passing, including default and variable-length arguments. Additionally, it discusses the properties of mutable and immutable objects, as well as mathematical and string functions available in Python libraries.

Uploaded by

sspslab9
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 25

New

syllab
us
2025-
26

Chapter
2
Functio
ns

Vaibhav Mishra , PGT Computer Science


Function
Introducti
A function is a
on
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 and
functions defined in module like
math.pow(),etc.But we can also create our
own functions. These
Vaibhav Mishra functions are called
, PGT Computer
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 : The length of the source
program can be reduced by using/calling functions at appropriate
places so program become more readable.
6.Function facilitates procedural abstraction : Once a function
is written, programmer
Vaibhav Mishrawould have
, PGT to know to invoke a function
Computer
Types of
functions:
1.Built- in functions
2. Functions defined in
module
3.User defined functions

Vaibhav Mishra , PGT Computer


1). Built-in
Functions which are already written or defined in python. As these
Functions:
functions are already defined so we do not need to define these
functions. Below are some built-in functions of Python.
Function name Description
len() It returns the length of an
list() object/value. It returns a list.
max() It is used to return maximum value from a sequence
min() (list,sets) etc. It is used to return minimum value from
open( a sequence (list,sets) etc. It is used to open a file.
) It is used to print statement.
print( It is used to return string object/value.
) str() It is used to sum the values inside
sum() sequence. It is used to return the
type() type of object.
tuple( It is used to return a tuple.
)

Vaibhav Mishra , PGT Computer


2). Functions defined in
module:
A module is a file consisting of Python code. A module
can define
functions, classes and variables.
Save this code in a file named
mymodule.py def greeting(name):
print("Hello, " + name)

Import the module named mymodule, and call the greeting

function: import mymodule

mymodule.greeting(“India")

Vaibhav Mishra , PGT Computer


3). User defined function:
Functions that we define ourselves to do certain
specific task are referred as user-defined functions
because these are not already available.

Vaibhav Mishra , PGT Computer


Creating & calling a
Function (user
defined)/Flow of execution
A function is defined using the def keyword
in python.E.g. program is given below.
#Function
def my_own_function(): block/
print("Hello from a definition/creati
on
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 itVaibhav Mishra , PGT Computer
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
Local variable program: Global variable program:
nonlocal keyword.
def fun(): def fun():
s = "I love India!" #local global s #accessing/making global variable
variable print(s) for fun() print(s)
s = "I love India!“ #changing global
s = "I love World!" variable’s value
fun() print(s)
print(s) s = "I love
Outpu world!" fun()
t: print(s)
I love Output:
India! I I love
love world! I
World! love India!
Vaibhav Mishra ,I PGT Computer
love
Variable’s Scope in
#Find the function
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)

Vaibhav Mishra , PGT Computer Science


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 Vaibhav Mishra , PGT Computer
Variable’s
Scope in
function
Global variables in nested function
def fun1():
x = 100
def fun2():
global x
x = 200
print("Before
calling
fun2: " + OUTPUT:
str(x))
Before calling
print("Calling
fun1()
fun2 fun2: 100 Calling
now:")
print("x in main: " + fun2 now: After
fun2()
str(x)) calling fun2: 100 x
print("After
in main: 200
calling
fun2: " +
str(x))

Vaibhav Mishra , PGT Computer


Variable’s
Scope in
Non local variable function
def
fun1():
x=
100
def
fun2():
nonloc
al x
print("After
#ch calling fun2: " + OUTPUT:
str(x))
ang Before calling
x=50e it fun2: 100 Calling
fun1()
to
print("x
globin main: " +
fun2 now: After
str(x))
al or calling fun2: 200 x
rem in main: 50
ove Vaibhav Mishra , PGT Computer
Function
Parameters / Arguments Passing and return
value
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 value/result
x,y=4,5
r=sum(x,y) #x, y are actual arguments
print(r)
Note :- 1. FunctionPrototype is declaration of
function with name
,argument and return
Vaibhav type.
Mishra 2. A formal parameter, i.e. a
, PGT Computer
Functio
Function n
Functions can be called using following types of formal arguments −
Arguments
• Required arguments/Positional parameter - arguments passed 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 #Keyword
• Variable-length arguments – pass multiple values with
arguments single argument name.
def
def fun( name, age ):
square(x) "This prints a passed info
: z=x*x into this function"
return z print ("Name: ", name)
print ("Age ",
r=square age) return;
()
print(r) # Now you
#In above function square() we can call
have to definitely need to pass printinfo
some value to argument x. function
fun( age=15,
name="mohak"
Vaibhav Mishra , PGT Computer
Function
#Default #Variable length
arguments def
arguments / sum( *vartuple ):
#Default s=0
for var in
Parameter vartuple:
def sum(x=3,y=4): s=s+int(var)
z=x+y return s;
return z
r=sum( 70, 60,
r=sum() 50 )
print(r) print(r)
r=sum(x= r=sum(4,
4) print(r) #now
5) the above function
r=sum(y= sum() can sum n number of
print(r)
45) values
print(r) Vaibhav Mishra , PGT Computer
Lamd
a
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
Vaibhav Mishra , PGT Computer
Mutable/immutable
properties
of data objects 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.
Immutable objects: int, float, tupl
Mutable objects:
frozen complex,list, dict, set, byte array
string, e,
set ,bytes Vaibhav Mishra , PGT Computer
Mutable/immutable
properties of data objects
w/rare
How objects function
passed to
#Pass by Functions#Pass by value
reference def def
updateList(list1): updateNumber(n
print(id(list ): print(id(n))
1)) list1 += n += 10
[10] print(id(n
print(id(list )) b = 5
1)) print(id(b))
n = [50, 60] updateNumb
print(id(n)) er(b) print(b)
updateList( print(id(b))
n) print(n) OUTPUT
print(id(n)) 1691040064
OUTPUT 1691040064
34122928 1691040224
34122928 5
34122928 1691040064
[50, 60, 10] #In above function value of
34122928 variable b is not being changed
Vaibhav
#In above function Mishra
list1 an object , PGT because
is being Computer it is immutable that’s why it
Functions using
libraries
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 Vaibhav Mishra , PGT Computer
Functions using
libraries
Functions available in Python Math
Module

Vaibhav Mishra , PGT Computer


Functions using
libraries (System
defined function)
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
Vaibhav Mishra , PGT Computer
Functions using
libraries
String
Method Description functions:
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
Searches the string for a specified value and returns the
find()
position of
where it was found
format() Formats specified values in a string
Searches the string for a specified value and returns the
index()
position Mishra
Vaibhav of , PGT Computer
Functions using
libraries String
Method Description functions:
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() ReturnsMishra
Vaibhav a left trim version
, PGT of the string
Computer
Functions using
libraries
String
functions:
Method Description

Returns a string where a specified value is replaced with


replace()
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


Vaibhav string, with
Mishra PGT a specified number of 0 values at the
Computer

You might also like