0% found this document useful (0 votes)
6 views31 pages

Functions 2

The document provides an overview of functions in Python, explaining their definition, advantages, types (built-in, module-defined, and user-defined), and how to create and call them. It also discusses variable scope, parameter passing, and the use of libraries for mathematical and string functions. Additionally, it highlights the concepts of mutable and immutable objects in relation to functions.

Uploaded by

aim_aim11
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views31 pages

Functions 2

The document provides an overview of functions in Python, explaining their definition, advantages, types (built-in, module-defined, and user-defined), and how to create and call them. It also discusses variable scope, parameter passing, and the use of libraries for mathematical and string functions. Additionally, it highlights the concepts of mutable and immutable objects in relation to functions.

Uploaded by

aim_aim11
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 31

Visit : python.mykvs.

in for regular updates

Chapter

Functions
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 userdefined functions.

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 would have to know to invoke a function
only ,not its coding.
7.Functions facilitate the factoring of code : A function can be called in
other function and so on…

Types of functions:
1.Built- in functions
2.Functions defined in module
3.User defined functions
1). Built-in Functions:
Functions which are already written or defined in python. As these
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 object/value.
list() It returns a list.
max() It is used to return maximum value from a sequence
(list,sets) etc.
min() It is used to return minimum value from a sequence
(list,sets) etc.
open() It is used to open a file.
print() It is used to print statement.
str() It is used to return string object/value.
sum() It is used to sum the values inside sequence.
type() It is used to return the type of object.
tuple() It is used to return a tuple.
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")
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.
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.

def my_own_function(): #Function block/definition/creation

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

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.
Global variable program:
Local variable program:
def fun(): global s #accessing/making global
def fun(): s = "I love India!"
variable for fun() print(s)
#local variable print(s) s = "I love India!“ #changing global
variable’s value print(s)
s = "I love World!" s = "I love world!"
fun() fun()
print(s) print(s)
Output: Output:
I love India! I love world!
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)
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
Variable’s Scope in
function print("After calling

Global variables in nested fun2: " + str(x))


function def fun1(): x = 100 def fun1()
fun2(): global x x = 200 print("x in main: " +
print("Before calling fun2: " + str(x))
str(x)) print("Calling fun2 now:")
OUTPUT:
fun2()
Before calling fun2: 100 Calling fun2 print("After calling
now: After calling fun2: 100 x in fun2: " + str(x))
main: 200
Variable’s Scope in
function
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()
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
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. 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
Function Arguments
Functions can be called using following types of formal 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.
• Variable-length arguments – pass multiple values with single argument name.
#Required arguments #Keyword
arguments def
def square(x): fun( name, age ):
z=x*x "This prints a passed info into
return z this function"
print ("Name: ",
r=square() name) print ("Age
print(r) ", age) return;
#In above function square() we
have to definitely need to pass # Now you can call printinfo
some value to argument x. function fun( age=15,
name="mohak" )
# value 15 and mohak is being
passed to relevant argument
based on keyword used for them.

Functio
n
#Default #Variable length
arguments def
arguments / sum( *vartuple ): s=0
#Default Parameter for var in 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(4,5)
r=sum(x=4) print(r)
print(r)
r=sum(y=45
) print(r) #now the above function
sum() can sum n number of
#default value of x and y is values
being used when it is not
passed

Lamda

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

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

How objects are passed to


Functions
#Pass by #Pass by value def
reference def updateNumber(n):
updateList(list1): print(id(n)) n +=
print(id(list1)) 10 print(id(n))
list1 += [10] b=5
print(id(list1)) print(id(b))
n = [50, 60] updateNumber(b)
print(id(n)) print(b)
updateList(n) print(id(b))
print(n) OUTPUT
print(id(n)) 1691040064
OUTPUT 1691040064
34122928 1691040224
34122928 5
34122928 1691040064
[50, 60, 10] #In above function value of variable b
34122928 is not being changed because it is
#In above function list1 an object is being immutable that’s why it is behaving
passed and its contents are changing like pass by value
because it is mutable that’s why it is
behaving like pass by reference
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
Functions using libraries
Functions available in Python Math
Module
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
Functions using
libraries

String functions:
Method Description
capitalize() Converts the first character to upper case
casefold()
Converts string into lower case
center()
count() Returns a centered string
encode() Returns the number of times a specified value occurs in
endswith() a string
find()
Returns an encoded version of the string
format()
index() Returns true if the string ends with the specified value
Searches the string for a specified value and returns the
position of where it was found
Formats specified values in a string
Searches the string for a specified value and returns the
position of where it was found
Functions using
libraries
String functions:
Method Description
isalnum() Returns True if all characters in the string are
isalpha() alphanumeric
isdecimal( Returns True if all characters in the string are in the
) isdigit() alphabet
isidentifie
Returns True if all characters in the string are decimals
r()
islower() Returns True if all characters in the string are digits
isnumeric( Returns True if the string is an identifier
) Returns True if all characters in the string are lower
isprintabl case
e() Returns True if all characters in the string are numeric
isspace()
Returns True if all characters in the string are printable
istitle()
isupper() Returns True if all characters in the string are
join() whitespaces
ljust() Returns True if the string follows the rules of a title
lower() Returns True if all characters in the string are upper
lstrip() case
partition() Joins the elements of an iterable to the end of the string
Returns a left justified version of the string
Converts a string into lower case
Returns a left trim version of the string
Returns a tuple where the string is parted into three
parts
Functions using
libraries
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
splitlines() a list
Splits the string at line breaks and returns a list
startswith(
Returns true if the string starts with the specified value
)
Swaps cases, lower case becomes upper case and vice
swapcase( versa
) Converts the first character of each word to upper case

title() Returns a translated string


translate() Converts a string into upper case
upper() Fills the string with a specified number of 0 values at
the beginning
zfill()

You might also like