0% found this document useful (0 votes)
134 views63 pages

Python Functions Guide by Dr. Arora

Uploaded by

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

Python Functions Guide by Dr. Arora

Uploaded by

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

COMPUTER

PROGRAMMING
USING PYTHON
FUNCTIONS
BY
DR VIPAN ARORA
1 Dr Vipan Arora
2

FUNCTIONS
 A function can be defined as the organized block of reusable
code, which can be called whenever required.
 Python allows us to divide a large program into the basic
building blocks known as a function. The function contains
the set of programming statements enclosed by {}.
 A function can be called multiple times to provide
reusability and modularity to the Python program.
 The Function helps to programmer to break the program
into the smaller part. It organizes the code very effectively
and avoids the repetition of the code. As the program grows,
function makes the program more organized.

Dr Vipan Arora
3

Dr Vipan Arora
4

Types of functions
 User-define functions - The user-defined
functions are those define by the user to
perform the specific task.
 Built-in functions - The built-in functions
are those functions that are pre-defined in
Python.

Dr Vipan Arora
5

Advantage of Functions
 Using functions, we can avoid rewriting the same
logic/code again and again in a program.
 We can call Python functions multiple times in a
program and anywhere in a program.
 We can track a large Python program easily when it
is divided into multiple functions.
 Reusability is the main achievement of Python
functions.
 However, Function calling is always overhead in a
Python program.
Dr Vipan Arora
6

Type of Functions
 Python Function are divided into three types
 User Defined Functions: A function that you
define yourself in a program is known as user
defined function. You can give any name to a user
defined function. In python, we define the user-
defined function using def keyword, followed by
the function name

Dr Vipan Arora
7

 Built In Functions: Built-in functions are those that are


predefined in Python libraries and user need not to declare these
functions before calling them. These functions can be freely
invoked as and when needed. The various built-in functions are :
 abs(x) for fetching the absolute value of x
 bin() for getting the binary value
 bool() for retrieving the boolean value of an object
 int() which will convert a string or number data type to an integer
data type
 list() for lists
 len() to get the length of the value
 open() to open the files
 pow() for returning the power of a number
 print() prints to the standard output device
 sum() for fetching the sum of the elements
 reversed() for reversing the order etc.
Dr Vipan Arora
8

 Modules : A Python module is a Python file


containing a set of functions and variables to be
used in an application. The variables can be of any
type (arrays, dictionaries, objects, etc.). Modules
can be either: Built in and User-defined.

Dr Vipan Arora
9

Why use functions


 Program : Write a program to convert
temperature from Fahrenheit to Celsius in
Python
# Enter temperature in Fahrenheit
f=float(input("Enter value in Fahrenheit"))
# Temperature in Celsius
c=((f-32)*5)/9
print("Temperature in Celsius is: ",c)
Dr Vipan Arora
10

Output

Dr Vipan Arora
11

 The above program is written and output is


obtained once. Now if we want to obtain the same
output 1000 times. This means we will write the
same lines of code 1000 times i.e. we need
multiple copies of the same program. Writing the
same program code again and again results in
waste of time, storage space, inefficiency and
ambiguity in the program.

Dr Vipan Arora
12

Dr Vipan Arora
13

 To resolve this problem, Python functions are used.


Instead of writing the code again and again a
function named conversion is created. Where ever in
the program the same code is required the function
conversion is called. This saves lot of time and
space and makes the program fast and efficient.
Functions enhances the reusability of the code in the
program i.e. code once written can be used again
and again. This makes code run better and faster

Dr Vipan Arora
14

Creating a Function
 Pythonprovides the def keyword to define the
function. The syntax of the define function is
given below
def fname(parameters):
function_block
return expression

Dr Vipan Arora
15

Dr Vipan Arora
16

 The def keyword, along with the function name is


used to define the function.
 The identifier rule must follow the function name.
 A function accepts the parameter (argument), and
they can be optional.
 The function block is started with the colon (:), and
block statements must be at the same indentation.
 The return statement is used to return the value. A
function can have only one return
Dr Vipan Arora
17

Function Calling
 In Python, after the function is created, we can call
it from another function.
 A function must be defined before the function
call; otherwise, the Python interpreter gives an
error.
 To call the function, use the function name
followed by the parentheses.

Dr Vipan Arora
18

#function definition
def hello_world():
print("hello world")
# function calling
hello_world()

Dr Vipan Arora
19

The return statement


 The return statement is used at the end of the
function and returns the result of the function. It
terminates the function execution and transfers the
result where the function is called. The return
statement cannot be used outside of the function.
return [expression_list]
 It can contain the expression which gets evaluated
and value is returned to the caller function. If the
return statement has no expression or does not exist
itself in the function then it returns the None object.
Dr Vipan Arora
20

Example
# Defining function
def sum():
a = 10
b = 20
c = a+b
return c
# calling sum() function in print statement
print("The sum is:",sum())
Dr Vipan Arora
21

Dr Vipan Arora
22

Creating function without return


statement
# Defining function
def sum():
a = 10
b = 20
c = a+b
# calling sum() function in print statement
print(sum())
 In the above code, we have defined the same function without
the return statement as we can see that the sum() function
returned the None object to the caller function.
Dr Vipan Arora
23

Arguments or Parameters
 Information can be passed into functions as
arguments.
 Arguments are specified after the function name,
inside the parentheses. You can add as many
arguments as you want, just separate them with a
comma.

Dr Vipan Arora
24

 The argument is a value that is passed to


the function when it's called.
 In other words on the calling side, it is an
argument and on the function side it is a
parameter.

Dr Vipan Arora
25

 Arguments are declared in the function definition.


While calling the function, you can pass the values
for that args as shown below

Dr Vipan Arora
26

 To declare a default value of an argument, assign


it a value at function definition.

 Example: x has no default values. Default values


of y=0. When we supply only one argument while
calling multiply function, Python assigns the
supplied value to x while keeping the value of
y=0. Hence the multiply of x*y=0

Dr Vipan Arora
27

 This time we will change the value to y=2 instead


of the default value y=0, and it will return the
output as (4x2)=8.

Dr Vipan Arora
28

 You can also change the order in which the


arguments can be passed in Python. Here we have
reversed the order of the value x and y to x=4 and
y=2.

Dr Vipan Arora
29

Function Arguments
You can call a function by using the following types
of formal arguments
Required arguments
Keyword arguments
Default arguments
Variable-length argument

Dr Vipan Arora
30

Required arguments
 Requiredarguments are the arguments passed to a
function in correct positional order. Here, the
number of arguments in the function call should
match exactly with the function definition.

Dr Vipan Arora
31

def printme( str ):


"This prints a passed string into this function"
print(str)
return;
# Now you can call printme function
printme()

Dr Vipan Arora
32

Default arguments
A default argument is a parameter
that assumes a default value if a
value is not provided in the
function call for that argument.
The following example illustrates
Default arguments.
Dr Vipan Arora
33

Python program to demonstrate


default arguments
# Python program to demonstrate default arguments
def myFun(x, y=50):
print("x: ", x)
print("y: ", y)
# Driver code with myFun() with only argument
myFun(10)

Output
X=10
Y=10
Dr Vipan Arora
34

# Function definition
def printinfo( name, age = 15 ):
"This prints a passed info into this function"
print("Name:",name)
print("Age",age)
return;
# Now you can call printinfo function
printinfo( age=18, name="Aman" )
printinfo( name="Aman" )
Dr Vipan Arora
35

Keyword arguments
 Keyword arguments are related to the function
calls. When you use keyword arguments in a
function call, the caller identifies the arguments by
the parameter name.
 This allows you to skip arguments or place them
out of order because the Python interpreter is able
to use the keywords provided to match the values
with parameters. You can also make keyword calls
to the printme() function in the following ways
Dr Vipan Arora
36

# Python program to demonstrate Keyword Arguments


def student(firstname, lastname):
print(firstname, lastname)

# Keyword arguments
student(firstname='Geeks', lastname='Practice')
student(lastname='Practice', firstname='Geeks')

Dr Vipan Arora
37

def printinfo( name, age ):


"This prints a passed info into this function"
print ("Name",name)
print ("Age",age)
return;

# Now you can call printinfo function


printinfo( age=50, name="Aman" )
Dr Vipan Arora
38

Variable-length arguments
 We can have both normal and keyword variable
number of arguments.
 You may need to process a function for more
arguments than you specified while defining the
function. These arguments are called variable-
length arguments and are not named in the
function definition, unlike required and default
arguments.

Dr Vipan Arora
39

def myFun(*argv):
for arg in argv:
print(arg)
myFun('Hello', 'Welcome', 'to', 'GeeksforGeeks')

Dr Vipan Arora
40

Pass by Value and Pass by


Reference
In programming language design, there are two
common paradigms for passing an argument to a
function:
 Pass-by-value: A copy of the argument is passed
to the function.
 Pass-by-reference: A reference to the argument is
passed to the function.

Dr Vipan Arora
41

In many programming languages, that’s essentially


the distinction between pass-by-value and pass-by-
reference:
 If a variable is passed by value, then the function
has a copy to work on, but it can’t modify the
original value in the calling environment.
 If a variable is passed by reference, then any
changes the function makes to the corresponding
parameter will affect the value in the calling
environment.

Dr Vipan Arora
42

In the diagram on the left, X has memory allocated in the main program’s
namespace. When F() is called, X is passed by value, so memory for the
corresponding parameter fx is allocated in the namespace of f(), and the
value of x is copied there. When f() modifies fx, it’s this local copy that is
changed. The value of x in the calling environment remains unaffected.

In the diagram on the right, x is passed by reference. The corresponding


parameter fx points to the actual address in the main program’s
namespace where the value of x is stored. When f() modifies fx, it’s
modifying the value in that location, just the same as if the main program
were modifying x itself. Dr Vipan Arora
43

Pass-By-Value vs Pass-By-
Reference in Python
 Are parameters in Python pass-by-value or pass-by-
reference? The answer is they’re neither, exactly.
That’s because a reference doesn’t mean quite the
same thing in Python as it does in other languages
 In Python, every piece of data is an object. A
reference points to an object, not a specific memory
location. That means assignment isn’t interpreted the
same way in Python as it is in other languages

Dr Vipan Arora
44

Data Binding in Programming


Languages
 Consider the following pair of statements in Python:
x := 5 x := 10
These are interpreted this way:
 The variable x references a specific memory location.
 The first statement puts the value 5 in that location.
 The next statement overwrites the 5 and puts 10 there
instead.

Dr Vipan Arora
45

Data Binding in Python


 By contrast, in Python, the analogous assignment
statements are as follows:
x=5
x = 10
These assignment statements have the following meaning:
 The first statement causes x to point to an object whose
value is 5.
 The next statement reassigns x as a new reference to a
different object whose value is 10. Stated another way, the
second assignment rebinds x to a different object with
value 10.
Dr Vipan Arora
46

 Python neither uses call by value nor call by


reference. It uses call-by-object-reference / call-
by-assignment that means:-
 When a mutable object like a list is passed to a
function, it performs call-by-reference.
 When an immutable object like a number, string,
or tuple is passed to a function, it performs call-
by-value

Dr Vipan Arora
47

Python program behaving as call by


value
def incr(x):
x=x+1

num=1
incr(num)
print(num)
If above function executes as call by value then output jas to be 1
and if it behaves as call by reference the output will be 2.
But the Output will be 1 because Python here
behaves as call by value.
Dr Vipan Arora
48

Python program behaving as call by


reference
def add_more(l):
l.append(5)

mylist=[1,2,3,4]
add_more(mylist)
print(mylist)
Output
[1,2,3,4,5]
Dr Vipan Arora
49

Dr Vipan Arora
50

 defval(x):
 x=15
 print(x,id(x))

 x=10
 val(x)
 print(x,id(x)

Dr Vipan Arora
Scope of Variables:
 All variables in a program may not be accessible at all locations in that program.
This depends on where you have declared a variable.
 The scope of a variable determines the portion of the program where you can
access a particular identifier. There are two basic scopes of variables in Python:
Global variables
Local variables
 Global vs. Local variables:
 Variables that are defined inside a function body have a local scope, and those
defined outside have a global scope.
 This means that local variables can be accessed only inside the function in which
they are declared whereas global variables can be accessed throughout the
program body by all functions. When you call a function, the variables declared
inside it are brought into scope.
 Example:
total = 0; # This is global variable.
def sum( arg1, arg2 ):
"Add both the parameters"
total = arg1 + arg2;
print "Inside the function local total : ", total
return total;
# Now you can call sum function
sum( 10, 20 );
print "Outside the function global total : ", total
 This would produce following result:
Inside the function local total : 30
Outside the function global total : 0
53

MAP
 Python’s map() is a built-in function that allows
you to process and transform all the items in an
iterable without using an explicit for loop, a
technique commonly known as mapping
 map() is useful when you need to apply
a transformation function to each item in an
iterable and transform them into a new iterable.
 map() is one of the tools that support a functional
programming in Python.
Dr Vipan Arora
54

Map() function
 The map() function applies the specified
function to every item of the passed iterable,
yields the results, and returns an iterator.
map(function, iterables) --> map object
 function: The function to be called for each element of
the specified iterable.
 iterables: One or more iterables separated by a comma
(such as string, list, tuple, dictionary)

Dr Vipan Arora
55

 Return Value: Returns an iterator object of


the map class.
 Consider the following simple square function.

def square(x):
return x*x

Dr Vipan Arora
56

>>> numbers=[1, 2, 3, 4, 5]
>>> sqrs_of_numbers=map(square, numbers)
>>> next(sqrs_of_numbers)
1
>>> next(sqrs_of_numbers)
4
>>> next(sqrs_of_numbers)
9
>>> next(sqrs_of_numbers)
16
>>> next(sqrs_of_numbers)
25
In the above example, the map() function applies to each element in
the numbers list. This will return an object of the map class, which is an
iterator, and so, we can use the next() function to traverse the list.
Dr Vipan Arora
57

FILTER
 Python filter() function is used to get filtered
elements. This function takes two arguments, first is
a function and the second is iterable. The filter
function returns a sequence from those elements of
iterable for which function returns True.
 The first argument can be None if the function is not
available and returns only elements that are True.
 The filter() function takes a function and a sequence as
arguments and returns an iterable, only yielding the
items in sequence for which function returns True.
 If None is passed instead of a function, all the items of
the sequence which evaluates to False are removed.

Dr Vipan Arora
58

 The syntax is as follows


filter (function, iterable)
 function: It is a function. If set to None returns
only elements that are True.
 Iterable: Any iterable sequence like list, tuple, and
string.
Both the parameters are required.
 Return :It returns the same as returned by the
function.

Dr Vipan Arora
59

This simple example returns values higher


than 5 using filter function.
# Python filter() function example
def filterdata(x):
if x>5:
return x
# Calling function
result = filter(filterdata,(1,2,6))
# Displaying result
print(list(result))
Dr Vipan Arora
60

Lambda
 A lambda function is a small anonymous function.
 A lambda function can take any number of
arguments, but can only have one expression.
 We use lambda functions when we require a
nameless function for a short period of time.
 The syntax is as follows

lambda arguments : expression


The expression is executed and the result is returned
Dr Vipan Arora
61

Add 10 to argument a, and return the


result:
x = lambda a : a + 10
print(x(5))
Lambda functions can take any number of arguments
Multiply argument a with argument b and return
the result
x = lambda a, b : a * b
print(x(5, 6))

Dr Vipan Arora
62

Inner Functions
A function which is defined inside another
function is known as inner function or nested
function. Nested functions are able to access
variables of the enclosing scope. Inner functions
are used so that they can be protected from
everything happening outside the function. This
process is also known as Encapsulation.

Dr Vipan Arora
63

Closures
 A closure is a nested function which has access to a free
variable from an enclosing function that has finished its
execution. Three characteristics of a Python closure are:
 it is a nested function
 it has access to a free variable in outer scope
 it is returned from the enclosing function
 A free variable is a variable that is not bound in the
local scope. In order for closures to work with
immutable variables such as numbers and strings, we
have to use the nonlocal keyword.
 Python closures help avoiding the usage of global
values and provide some form of data hiding. They
are used in Python decorators. Dr Vipan Arora

You might also like