0% found this document useful (0 votes)
2 views39 pages

7.PythonProgramming Module 5a

The document provides an overview of Python programming, focusing on functions and modules. It explains the types of functions, the difference between parameters and arguments, and how to define user-defined functions. Additionally, it covers variable arguments, recursion, lambda functions, and the map() function.

Uploaded by

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

7.PythonProgramming Module 5a

The document provides an overview of Python programming, focusing on functions and modules. It explains the types of functions, the difference between parameters and arguments, and how to define user-defined functions. Additionally, it covers variable arguments, recursion, lambda functions, and the map() function.

Uploaded by

sjlkuikel
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

PMDS508L - Python Programming

Functions and Modules

Dr. B.S.R.V. Prasad


Department of Mathematics
School of Advanced Sciences
Vellore Institute of Technology
Vellore

[Link]@[Link] (Personal)
[Link]@[Link] (Official)
+91-8220417476
Functions 1

▶ A function is a block of code which can be run when it is called.


▶ Functions can be re-used and reduce the programming complexity.
▶ In other words, a function is a piece of code written to carry out a specified
task.
▶ To carry out that specific task, the function might or might not need multiple
inputs (arguments).
▶ When the task is carried out, the function can or can not return one or more
values.

Dr. B.S.R.V. Prasad | PMDS508L - Python Programming


Python Functions 2

▶ There are three types of functions in Python:


▶ Built-in functions, such as help() to ask for help, min() to get the minimum
value, print() to print an object to the terminal,. . . You can find an overview
with more of these functions here.
▶ User-Defined Functions (UDFs), which are functions that users create to help
them out; And
▶ Anonymous functions, which are also called lambda functions because they
are not declared with the standard def keyword.

Dr. B.S.R.V. Prasad | PMDS508L - Python Programming


Parameters vs Arguments 3

▶ The parameters are the variables that we can define in the function
declaration.
▶ The arguments are the variables given to the function for execution.
▶ In other words, parameters are the names used when defining a function or
a method, and into which arguments will be mapped.
▶ Arguments are the things which are supplied to any function, while the
function code refers to the arguments by their parameters.
▶ Parameters are local variables which are assigned values of the arguments
when the function is called.
▶ Parameters are known as Formal Parameters and arguments are known as
Actual Parameters.
Dr. B.S.R.V. Prasad | PMDS508L - Python Programming
User-Defined Functions 4

In Python a user-defined function is defined using the following four-steps:


1. Use the keyword def to declare the function and follow this up with the
function name.
2. Add parameters to the function: they should be within the parentheses of
the function. End your line with a colon.
3. Add statements that the functions should execute.
4. End your function with a return statement if the function should output
something. Without the return statement, your function will return an object
None.

Dr. B.S.R.V. Prasad | PMDS508L - Python Programming


User-Defined Functions 5

1 def my_first_function () :
2 print ( " Hellooo .. This is my first function ")
3

4 my_first_function ()

Dr. B.S.R.V. Prasad | PMDS508L - Python Programming


Python Functions
The return Statement 6

▶ If we want to continue to work with the result of your function and try out some operations on it,
we will need to use the return statement to actually return a value, such as a String, an integer, etc.
▶ If we are only printing a message then we don’t need to return any value.

1 def hello () :
2 print (" Hello World ")
3 return (" hello ")
4

5 def hello_noreturn () :
6 print (" Hello World ")
7

8 hello () * 2 # Multiply the output of ` hello () ` with 2


9

10 hello_noreturn () * 2 # ( Try to ) multiply the output of `


hello_noreturn () ` with 2

Dr. B.S.R.V. Prasad | PMDS508L - Python Programming


Python Funcitons
The return Statement 7

Functions immediately exit when they come across a return statement, even if it
means that they won’t return any value:
1 def test_fun () :
2 for x in range (10) :
3 if x == 5:
4 return
5 print ( " Run ! ")
6

7 test_fun ()

Dr. B.S.R.V. Prasad | PMDS508L - Python Programming


Python Funcitons
The return Statement 8

Another thing that is worth mentioning when we’re working with the return
statement, we can use it to return multiple values.
1 # Define ' plus () '
2 def plus (a ,b):
3 sumab = a + b
4 return ( sumab , a)
5

6 # Call ' plus () '


7 sumab , a = plus (3 ,4)
8

9 print ( sumab ) # Print ' sumab '


10 print ( sumab , ' ',a) # Print ' sumab ' and 'a '
11 print ( sumab , ' ' ,b) # Error
Dr. B.S.R.V. Prasad | PMDS508L - Python Programming
Python Functions
Function Arguments 9

We can pass arguments to functions and can evaluate them inside the function
block.
1 def addnums ( num1 , num2 ):
2 print ( " The num1 is : " , num1 )
3 print ( " The num2 is : " , num2 )
4 print ( " The sum of the two numbers is : " , num1 + num2 )
5

6 addnums (2 ,3)
7 addnums ( -5 ,6)
8 addnums (10.5 , 2.6)
9 addnums (10.5 ,2)

Dr. B.S.R.V. Prasad | PMDS508L - Python Programming


Python Functions
Function Arguments 10

▶ By default, a function must be called with the correct number of arguments.


▶ If you try to call the function with lesser or greater arguments, the Python
returns an error.

Dr. B.S.R.V. Prasad | PMDS508L - Python Programming


Python Functions
Variable [Link] Arguments 11

▶ We can even pass the arbitrary number of arguments into a function.


▶ For this we add * before the parameter name in the function definition
▶ There are two types of variable arguments in Python.
▶ *args for Non-Keyword Arguments
▶ **kwargs for Keyword Arguments

Dr. B.S.R.V. Prasad | PMDS508L - Python Programming


Python Functions
Variable [Link] Arguments 12

▶ The *args in Python function definitions is used to pass a non-key worded,


variable number of arguments to a function.

Dr. B.S.R.V. Prasad | PMDS508L - Python Programming


Python Functions
Variable [Link] Arguments 12

▶ The *args in Python function definitions is used to pass a non-key worded,


variable number of arguments to a function.
1 def my_function (* args ):
2 l = len ( args )
3 print ( " The number of arguments passed are : " ,l)
4 for i in range (0 , l):
5 print ( ' Argument ',i +1 , 'is : ', args [i ])
6

7 my_function (2 ,6)
8 my_function ( " a")
9 my_function (2 , "a" ,3.4)
10 my_function (2 , "a" ,[3 ,5.7 , " Test " ])
Dr. B.S.R.V. Prasad | PMDS508L - Python Programming
Python Functions
Variable [Link] Arguments 13

▶ The **kwargs in function definitions in python is used to pass a keyworded,


variable-length argument list.
▶ We use the name kwargs with the double star.
▶ A keyword argument is where you provide a name to the variable as you pass
it into the function.
▶ One can think of the kwargs as being a dictionary that maps each keyword to
the value that we pass alongside it.
▶ As a result, we can iterate over the kwargs and perform the necessary
operations in a function call.

Dr. B.S.R.V. Prasad | PMDS508L - Python Programming


Python Functions
Variable [Link] Arguments 14

1 def my_function (** kwargs ):


2 for key , value in kwargs . items () :
3 print ( ' Key = ',key , '; Value = ' , value )
4

5 my_function ( First =" One " , Second =34.5 , Third = True )


6 my_function ( First =1)
7 my_function ( Name =" Prasad " , Degree =" PhD ")
8 my_function ( Key1 =2 , Key2 ="a" , Key3 =[3 ,5.7 , " Test " ])

Dr. B.S.R.V. Prasad | PMDS508L - Python Programming


Python Functions
Use of *args and **kwargs 15

1 def my_function (* args , ** kwargs ):


2 print ( " args : " , args )
3 print ( " kwargs : " , kwargs )
4

5 my_function ( ' one ', 2, 3.14 , first =" Prasad " , last ="
Bhuvanagiri " , degree =" PhD ")

Dr. B.S.R.V. Prasad | PMDS508L - Python Programming


Python Functions
Default Parameter Values 16

We can use default parameter values for a function as follows:


1 def addnums ( num1 =0 , num2 =0) :
2 print ( " The num1 is : " , num1 )
3 print ( " The num2 is : " , num2 )
4 print ( " The sum of the two numbers is : " , num1 + num2 )
5

6 addnums (2 ,3)
7 addnums (2)
8 addnums ( num2 =3)
9 addnums ( num1 =5.6)
10 addnums ()

Dr. B.S.R.V. Prasad | PMDS508L - Python Programming


Python Functions
List of Arguments 17

We can even pass a List as an argument to Python function


1 def addnums ( myNums ):
2 numsum = 0
3 for i in myNums :
4 numsum += i
5 print ( " The sum of the numbers is : " , numsum )
6

7 addnums ([1 , 20 , 43 , 52])

Dr. B.S.R.V. Prasad | PMDS508L - Python Programming


Python Functions
Returning a Value 18

Functions can return a value to the user:


1 def addnums ( myNums ):
2 numsum = 0
3 for i in myNums :
4 numsum += i
5 return numsum
6

7 print ( " The sum of numbers is : " , addnums ([1 , 20 , 43 ,


52]) )

Dr. B.S.R.V. Prasad | PMDS508L - Python Programming


Scope of the Variables in Python Functions 19

▶ In general, variables that are defined inside a function body have a local
scope, and those defined outside have a global scope.
▶ That means that local variables are defined within a function block and can
only be accessed inside that function, while global variables can be obtained
by all functions that might be in our script.

Dr. B.S.R.V. Prasad | PMDS508L - Python Programming


Global vs Local Variables 20

1 # Global variable init


2 init = 1
3

4 # Define plus () function to accept a variable number of arguments


5 def plus (* args ):
6 # Local variable total
7 total = 0
8 print ( ' The initial value is : ', init )
9 for i in args :
10 total += i
11 return total
12

13 # Access the global variable


14 print ( " this is the initialized value " + str ( init ))
15

16 # ( Try to ) access the local variable


17 print ( " this is the sum " + str ( total ))
Dr. B.S.R.V. Prasad | PMDS508L - Python Programming
Recursive Functions 21

▶ Recursion is a mathematical and programming concept, in which a function


calls itself.
▶ This has the benefit that one can loop through data to reach a result.
▶ Recursion is a very efficient and mathematically-elegant approach to
programming
▶ Developer/Programmer should be very careful while designing a recursion.
▶ It can be quite easy to slip into writing a recursion which never terminates, or
uses excess amounts of memory or processor power.

Dr. B.S.R.V. Prasad | PMDS508L - Python Programming


Recursive Functions 22

1 def my_recursion ( num ):


2 if ( num > 0) :
3 result = num + my_recursion ( num -1)
4 print ( result )
5 else :
6 result = 0
7 return result
8

9 print ( " \ nMy Recursion Example Results :")


10 finalAns = my_recursion (6)
11 print ( " \ nThe Final Answer is : " , finalAns )

Dr. B.S.R.V. Prasad | PMDS508L - Python Programming


Lambda Function 23

▶ We can write our very own Python functions using the def keyword, function
headers, docstrings, and function bodies.
▶ However, there’s a quicker way to write functions on the fly, and these are
called lambda functions because you use the keyword lambda.
▶ A lambda function is a small anonymous function.
▶ A lambda function can take any number of arguments, but can only have one
expression.

Dr. B.S.R.V. Prasad | PMDS508L - Python Programming


Lambda Function 24

Syntax
1 fn = lambda arguments : expression

Dr. B.S.R.V. Prasad | PMDS508L - Python Programming


Lambda Function 25

1 raise_to_power = lambda x , y: x ** y
2

3 raise_to_power (2 , 3)

1 myfunc = lambda a , b , c : a+b*c


2

3 print ( myfunc (2 ,3 ,5) )

Dr. B.S.R.V. Prasad | PMDS508L - Python Programming


map() function 26

The map() function executes a specified function for each item in an iterable. The
item is sent to the function as a parameter.
1 map ( function , iterables )
function: (Required) The function to execute on each item.
iterables: (Required) A sequence, collection or an iterator object.
We can send as many iterables as we like. But need to make sure
that the function has one parameter for each iterable.

Dr. B.S.R.V. Prasad | PMDS508L - Python Programming


map() function 27

1 def myFunc (a , b):


2 return a + b
3

4 x = map ( myFunc , ( ' apple ', ' banana ', ' cherry ') , ( ' orange
' , ' lemon ' , ' pineapple '))
5

6 print ( x ) # returns a map object


7 print ( list ( x ) ) # convert the map into a list , for
readability

Dr. B.S.R.V. Prasad | PMDS508L - Python Programming


map() function 28

1 def myFunc ( x ) :
2 return x **2
3

4 X = map ( myFunc , [1 ,5 , -2 ,3])


5

6 print ( X ) # returns a map object


7 print ( list ( X ) ) # convert the map into a list , for
readability

Dr. B.S.R.V. Prasad | PMDS508L - Python Programming


map() function with lambda function 29

We can pass lambda function to the map() without even naming them, and in this
case, we refer to them as anonymous functions.
1 nums = [48 , 6 , 9, 21 , 1]
2

3 square_all = map ( lambda num : num ** 2, nums )


4

5 print ( square_all ) # Returns a map object


6

7 print ( list ( square_all )) # To see what the above map


object returns , we use list to turn into a list

Dr. B.S.R.V. Prasad | PMDS508L - Python Programming


filter() function 30

The filter() function returns an iterator where the items are filtered through a
function to test if the item is accepted or not.
1 filter ( function , iterable )
function: (Required) The function to execute on each item.
iterables: (Required) A sequence, collection or an iterator
object.

Dr. B.S.R.V. Prasad | PMDS508L - Python Programming


filter() function 31

1 ages = [5 , 12 , 17 , 18 , 24 , 32]
2

3 def myFunc ( x ) :
4 if x < 18:
5 return False
6 else :
7 return True
8

9 adults = filter ( myFunc , ages )


10

11 for x in adults :
12 print ( x )
Dr. B.S.R.V. Prasad | PMDS508L - Python Programming
filter() function 32

1 # function that filters vowels


2 def fun ( variable ):
3 letters = [ 'a ', 'e ', 'i ', 'o ', 'u ']
4 if ( variable in letters ):
5 return True
6 else :
7 return False
8

9 sequence = [ 'b ', 'e ', 'i ', 'l ', 'k ', 's ' , 'p ' , 'a ']
10 filtered = filter ( fun , sequence ) # using filter function
11

12 print ( ' The filtered letters are : ')


13 for s in filtered :
14 print ( s)
Dr. B.S.R.V. Prasad | PMDS508L - Python Programming
filter() function with lambda function 33

1 my_list = [1 ,2 ,3 ,4 ,5 ,6 ,7 ,8 ,9 ,10]
2

3 # Use lambda function with ` filter () `


4 filtered_list = list ( filter ( lambda x: (x *2 > 10) ,
my_list ) )
5

6 print ( filtered_list )

Dr. B.S.R.V. Prasad | PMDS508L - Python Programming


Functions with function arguments
Higher order functions 34

▶ Python functions are nothing but objects and names we define are simply
identifiers bound to these objects.
1 def first ( msg ):
2 print ( msg )
3

4 first ( " Hello ")


5

6 second = first
7 second ( " Hello ")
▶ When we run the above code both functions first and second Return the
same output as both refers to same object.
Dr. B.S.R.V. Prasad | PMDS508L - Python Programming
Functions with function arguments
Higher order functions 35

▶ We can even pass a function as argument to other function and these functions are called
higher order functions
1 def inc ( x ) :
2 return x + 1
3

4 def dec ( x ) :
5 return x - 1
6

7 def operate ( func , x):


8 result = func (x)
9 return result
10

11 operate ( inc , 3)
12 operate ( dec , 3)
Dr. B.S.R.V. Prasad | PMDS508L - Python Programming
Nested Functions 36

▶ A function can return another function


1 def fun_called () :
2 def fun_returned () :
3 print (" Hello !.. from inner function ")
4 return fun_returned
5

6 new = fun_called () # Create the fun_called object


7

8 new () # Call the function new ()


9

10 # Output : Hello !.. from inner function

Dr. B.S.R.V. Prasad | PMDS508L - Python Programming


Nested Functions 37

▶ Nested functions can access variables of the enclosing scope.


▶ Following is an example of a nested function accessing a non-local variable (a
variable which is read-only by default)
1 def outer_fn ( msg ): # Outer function
2 def inner_fn () :
3 print (" Printing from inner function with
argument passed to outer function \n"+ msg )
4 inner_fn ()
5

6 outer_fn ( " Hello !.. Argument passed to outer function


")

Dr. B.S.R.V. Prasad | PMDS508L - Python Programming

You might also like