0% found this document useful (0 votes)
29 views54 pages

MODULE 3 - Python Functions - Python Programming

unit 3
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
0% found this document useful (0 votes)
29 views54 pages

MODULE 3 - Python Functions - Python Programming

unit 3
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1/ 54

PYTHON PROGRAMMING:

MODULE 3 – PYTHON FUNCTIONS


Prof J. Noorul Ameen M.E,(Ph.D), EMCAA, MISTE, D.Acu.,
Assistant Professor/CSE
Member – Centre for Technology & Capability Development
E.G.S Pillay Engineering College, Nagapattinam

9150132532
noornilo@gmail.com
Profameencse.weebly.com Noornilo Nafees 1
MODULE 3 – PYTHON FUNCTIONS
 At the end of this course students can able to
 Understand the concept of function and their

types.
 Know the difference between User defined

and Built in functions.


 Know how to call a function.
 Understand the function arguments.
 Know Anonymous functions.
 Know Mathematical and some String
functions.
Noornilo Nafees 2
PYTHON FUNCTIONS
 Functions are named blocks of code that are
designed to do specific job.
 When you want to perform a particular task that you

have defined in a function, you call the name of the


function responsible for it.
 If you need to perform that task multiple times

throughout your program, you don’t need to type all


the code for the same task again and again; you just
call the function dedicated to handling that task, and
the call tells Python to run the code inside the
function.
 Functions makes your programs easier to write, read,

test, and fix errors.


Noornilo Nafees 3
 Types of functions in Python:
 (a) User defined Functions
 (b) Lambda Functions
 (c) Recursive Functions
 (d) Built in Functions
FUNCTIONS DESCRIPTION
User-defined functions Functions defined by the users themselves.
Built-in functions Functions that are inbuilt with in Python.
Lambda functions Functions that are anonymous un-named function.

Recursive functions Functions that calls itself is known as recursive.

 Advantages of functions:
 It avoids repetition and makes high degree of code
reusing.
 It provides better modularity for your application.
Noornilo Nafees 4
 Defining Functions: Functions must be defined, to
create and use certain functionality.
 When defining functions there are multiple things that
need to be noted such as:
 Function blocks begin with the keyword “def” followed
by function name and parenthesis ().
 Any input parameters or arguments should be placed
within these parentheses when you define a function.
 The code block always comes after a colon (:) and is
indented.
 The statement “return [expression]” exits a function,
optionally passing back an expression to the caller.
 A “return” with no arguments is the same as return
None.
 Python keywords should not be used as function name.
Noornilo Nafees 5
 (a) Syntax for User defined function: Functions defined by
 the users themselves.

 def <function_name ([parameter1, parameter2…] )> :

◦ <Block of Statements>
◦ return <expression / None>
 def hello():

◦ print (“hello - Python”)


◦ return
 Calling a Function: When you call the “hello()” function, the

program displays the following string as


 def hello():

◦ print (“hello - Python”)


◦ return
 hello()

 Output:

 hello – Python Noornilo Nafees 6


 Passing Parameters in Functions:
 def function_name (parameter(s) separated by comma):
 The parameters that you place in the parenthesis will be used by the
function itself.
 Here is an example program that defines a function that helps to
pass parameters into the function.
 Example:
 # assume w = 3 and h = 5
 def area(w,h):
◦ return w * h
◦ print (area (3,5))
 The above code assigns the width and height values to the
parameters w and h.
 These parameters are used in the creation of the function “area”.
 When you call the above function, it returns the product of width
and height as output.
 The value of 3 and 5 are passed to w and h respectively, the
function will return 15 as output. Noornilo Nafees 7
 Function Arguments:
 These are used to call a function and there are

primarily 4 types
 (i) Required arguments
 (ii) Keyword arguments
 (iii) Default arguments
 (iv) Variable-length arguments

Noornilo Nafees 8
 (i) Required arguments: These 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.
 You need at least one parameter to prevent syntax errors
and to get the required output.
 Example :
 def printstring(str):
◦ print ("Example - Required arguments ")
◦ print (str)
◦ return
 # Now you can call printstring() function
 printstring(“Meeran”)
 Output:
Example - Required arguments
 Meeran Noornilo Nafees 9
 (ii) Keyword Arguments: These arguments will invoke the
function after the parameters are recognized by their parameter
names.
 The value of the keyword argument is matched with the
parameter name and so, one can also put arguments in
improper order.
 Example:
 def printdata (name):
◦ print (“Example-1 Keyword arguments”)
◦ print (“Name :”,name)
◦ Return
 printdata(name = “Nilo”)
 Output:
 Example-1 Keyword arguments
 Name : Nilo

Noornilo Nafees 10
 Example:
 def printdata (name, age):
◦ print ("Example-3 Keyword arguments")
◦ print ("Name :",name)
◦ print ("Age :",age)
◦ return
 # Now you can call printdata() function
 printdata (age=7, name=“Nafees")
 Output:
 Example-2 Keyword arguments
 Name : Nafees
 Age: 7
 In the above program the parameters orders are changed

Noornilo Nafees 11
 (iii)Default Arguments: In Python the default argument
is an argument that takes a default value if no value is
provided in the function call.
 The following example uses default arguments, that
prints default salary when no argument is passed.
 Example:
 def printinfo( name, salary = 3500):
◦ print (“Name: “, name)
◦ print (“Salary: “, salary)
◦ return
 printinfo(“Noor”)
 Output:
 Name: Noor
 Salary: 3500
Noornilo Nafees 12
 Example:
 def printinfo( name, salary = 3500):

◦ print (“Name: “, name)


◦ print (“Salary: “, salary)
◦ return
 printinfo(“Nilo,50000”)
 Output:
 Name: Nilo
 Salary: 50000
 In the above code, the value 50000 is passed to the

argument salary, the default value already assigned for


salary 3500 is simply ignored.

Noornilo Nafees 13
 (iv) Variable-Length Arguments:
 In some instances you might need to pass more

arguments than have already been specified.


 Going back to the function to redefine it can be a

tedious process.
 Variable-Length arguments can be used instead.
 These are not specified in the function’s definition and

an asterisk (*) is used to define such arguments.


 Syntax - Variable-Length Arguments
 def function_name(*args):

◦ function_body
◦ return_statement

Noornilo Nafees 14
 Example:
 def printnos (*nos):
 for n in nos:
◦ print(n) Output:
Printing two values
◦ return
1
 # now invoking the printnos() function 2
 print ('Printing two values') Printing three values
 printnos (1,2) 10
 print ('Printing three values') 20
 printnos (10,20,30) 30

Noornilo Nafees 15
 (b) Lambda/Anonymous Functions: In Python,
anonymous function is a function that is defined without
a name.
 While normal functions are defined using the def
keyword, in Python anonymous functions are defined
using the lambda keyword.
 Hence, anonymous functions are also called as lambda
functions.
 What is the use of lambda or anonymous function?
 Lambda function is mostly used for creating small and
one-time anonymous function.
 Lambda function can take any number of arguments and
must return one value in the form of an expression.
 Lambda function can only access global variables and
variables in its parameter list.
Noornilo Nafees 16
 Syntax of Lambda Functions:
 The syntax for anonymous functions is as follows:
 lambda [argument(s)] :expression
 Example:
 sum = lambda arg1, arg2: arg1 + arg2
 print ('The Sum is :', sum(30,40))
 print ('The Sum is :', sum(-30,40))
 Output:
 The Sum is : 70
 The Sum is : 10

Noornilo Nafees 17
 The return statement: The return statement causes
your function to exit and returns a value to its caller.
 The point of functions in general is to take inputs and

return something.
 The return statement is used when a function is

ready to return a value to its caller.


 Syntax of return:
 return [expression list ]
 This statement can contain expression which gets

evaluated and the value is returned.

Noornilo Nafees 18
 Example:
 def usr_abs (n):
◦ if n>=0:
 return n
◦ else:
 return –n
 x=int (input(“Enter a number :”)
 print (usr_abs (x))
 Output 1:
 Enter a number : 25
 25
 Output 2:
 Enter a number : -25
 25

Noornilo Nafees 19
 (c) Recursive Functions: When a function calls itself is
known as recursion.
 Example:
 def fact(n):
◦ if n == 0:
 return 1
◦ else:
 return n * fact (n-1)
 print (fact (0))
 print (fact (5))
 Output:
 1
 120

Noornilo Nafees 20
 Built-in and Mathematical functions:
 Functions using libraries:
 1. abs ( )
 Returns an absolute value of a number.

The argument may be an integer or a floating point number.


 Syntax: abs (x)
 Example:
 x=20
 y=-23.2
 print('x = ', abs(x))
 print('y = ', abs(y))
 Output:
 x = 20
 y = 23.2
Noornilo Nafees 21
 2. ord ( )
 Returns the ASCII value for the given Unicode

character.
 This function is inverse of chr() function.
 Syntax: ord (c)
 Example:
 c= 'a'
 d= 'A'
 print ('c = ',ord (c))
 print ('A = ',ord (d))
 Output:
 c = 97
 A = 65
Noornilo Nafees 22
 3. chr ( )
 Returns the Unicode character for the given ASCII

value.
 This function is inverse of ord() function.
 Syntax: chr (i)
 Example:
 c=65
 d=43
 print (chr (c))
 print(chr (d))
 Output:
 A
 +
Noornilo Nafees 23
 4. bin ( )
 Returns a binary string prefixed with “0b” for the

given integer number.


 Note: format() can also be used instead of this

function.
 Syntax: bin(i)
 Example:
 x=15
 y=101
 print ('15 in binary : ',bin (x))
 print ('101 in binary : ',bin (y))
 Output:
 15 in binary : 0b1111
 101 in binary : 0b1100101
Noornilo Nafees 24
 5. type ( )
 Returns the type of object for the given single object.
 This function used with single object parameter.
 Syntax: type(object)
 Example:
 x= 15.2
 y= 'a'
 s= True
 print (type (x))
 print (type (y))
 print (type (s))
 Output:
 <class 'float'>
 <class 'str'>
 <class 'bool'>
Noornilo Nafees 25
 6. id ( )
 id( ) return the the address of the object in memory.
 Syntax: id(object)
 Example:
 x=15
 y='a'
 print (‘Address of x is :',id (x))
 print (‘Address of y is :',id (y))
 Output:
 Address of x is : 1357486752
 Address of y is : 13480736

Noornilo Nafees 26
 7. min ( )
 Returns the minimum value in a list.
 Syntax: min(list)
 Example:
 MyList = [21,76,98,23]
 print ('Minimum of MyList :', min(MyList))
 Output:
 Minimum of MyList : 21

Noornilo Nafees 27
 8. max ( )
 Returns the maximum value in a list.
 Syntax: max(list)
 Example:
 MyList = [21,76,98,23]
 print ('Maximum of MyList :', max(MyList))
 Output:
 Minimum of MyList : 98

Noornilo Nafees 28
 9. sum ( )
 Returns the sum of values in a list.
 Syntax: sum(list)
 Example:
 MyList = [21,76,98,23]
 print (‘Sum of MyList :', sum(MyList))
 Output:
 Sum of MyList : 218

Noornilo Nafees 29
 10. format() Returns the output based on the given
format
 a. Binary format: Outputs the number in base 2.
 b. Octal format: Outputs the number in base 8.
 c. Fixed-point notation: Displays the number as a

fixed-point number.
 The default precision is 6.
 Syntax: format (value, [format_spec])

Noornilo Nafees 30
 Example:
 x= 14
 y= 25
 print ('x value in binary :',format(x,'b'))
 print ('y value in octal :',format(y,'o'))
 print('y value in Fixed-point no ',format(y,'f '))
 Output:
 x value in binary : 1110
 y value in octal : 31
 y value in Fixed-point no : 25.000000

Noornilo Nafees 31
 11. round ( ) Returns the nearest integer to its input.
 First argument (number)is used to specify the value

to be rounded.
 Second argument is used to specify the number of

decimal digits desired after rounding.


 Syntax: round(number,[ndigits])

Noornilo Nafees 32
 Example:
 x= 17.9
 y= 22.2
 z= -18.3
 print ('x value is rounded to', round (x))
 print ('y value is rounded to', round (y))
 print ('z value is rounded to', round (z))
 Output:
 x value is rounded to 18
 y value is rounded to 22
 z value is rounded to -18

Noornilo Nafees 33
 Example:
 n1=17.89
 print (round (n1,0))
 print (round (n1,1))
 print (round (n1,2))
 Output:
 18.0
 17.9
 17.89

Noornilo Nafees 34
 12. pow()
 Returns the computation of ab i.e. (a**b )
 a raised to the power of b.
 Syntax: pow(a,b)
 Example:
 a= 5
 b= 2
 c= 3.0
 print (pow (a,b))
 print (pow (a,c))
 print (pow (a+b,3))
 Output:
 25
 125.0
 343
Noornilo Nafees 35
 13. floor() Returns the largest integer less than or equal to x
 Syntax: math.floor (x)
 Example:
 import math
 x=26.7
 y=-26.7
 z=-23.2
 print (math.floor (x))
 print (math.floor (y))
 print (math.floor (z))
 Output:
 26
 -27
 -24
Noornilo Nafees 36
 14. ceil ( ) Returns the smallest integer greater than or equal to x
 Syntax: math.ceil (x)
 Example:
 import math
 x= 26.7
 y= -26.7
 z= -23.2
 print (math.ceil (x))
 print (math.ceil (y))
 print (math.ceil (z))
 Output:
 27
 -26
 -23

Noornilo Nafees 37
 15. sqrt ( ) Returns the square root of x
 Syntax: sqrt (x)
 Example:
 import math
 a= 30
 b= 49
 c= 25.5
 print (math.sqrt (a))
 print (math.sqrt (b))
 print (math.sqrt (c))
 Output:
 5.477225575051661
 7.0
 5.049752469181039
Noornilo Nafees 38
 Composition in functions: The value returned by a function
may be used as an argument for another function in a nested
manner. This is called composition.
 For example, if we wish to take a numeric value or an
expression as a input from the user, we take the input string
from the user using the function input() and apply eval()
function to evaluate its value, for example:
 # This program explains composition
 >>> n1 = eval (input ("Enter a number: "))
 Enter a number: 234
 >>> n1
 234
 >>> n2 = eval (input ("Enter an arithmetic expression: "))
 Enter an arithmetic expression: 12.0+13.0 * 2
 >>> n2
 38.0
Noornilo Nafees 39
 Scope of Variables: It refers to the part of the program,
where it is accessible.
 Types of scopes:
 (a) Local scope
 (b) Global scope
 (a) Local scope: A variable declared inside the function's
body or in the local scope is known as local variable.
 Rules of local variable:
 A variable with local scope can be accessed only within
the function/block that it is created in.
 When a variable is created inside the function/block, the
variable becomes local to it.
 A local variable only exists while the function is
executing.
 The formal arguments are also local to function.
Noornilo Nafees 40
 Example: Local Variable
 def loc():

◦ y=0 # local scope


◦ print(y)
 loc()
 Output:
 0

Noornilo Nafees 41
 Global Scope: A variable, with global scope can be
used anywhere in the program.
 It can be created by defining a variable outside the

scope of any function/block.


 Rules of global Keyword:
 The basic rules for global keyword in Python are:
 When we define a variable outside a function, it’s

global by default. You don’t have to use global


keyword.
 We use global keyword to read and write a global

variable inside a function.


 Use of global keyword outside a function has no

effect
Noornilo Nafees 42
 Example: Accessing global Variable From Inside a
Function
 c = 1 # global variable
 def add():

◦ print(c)
 add()
 Output:
 1

Noornilo Nafees 43
 Modifying Global Variable From Inside the Function:
 Without using the global keyword we cannot modify

the global variable inside the function but we can only


access the global variable.
 x = 0 # global variable
 def add():

◦ global x
◦ x = x + 5 # increment by 2
◦ print ("Inside add() function x value is :", x)
 add()
 Output:
 Inside add() function x value is : 5

Noornilo Nafees 44
 Global variable and Local variable with same name:
 x=5
 def loc():
◦ x = 10
◦ print ("local x:", x)
 loc()
 print ("global x:", x)
 Output:
 local x: 10
 global x: 5
 In above code, we used same name ‘x’ for both global
variable and local variable.
 We will get different result when we print same variable,
because the variable is declared in both scopes, i.e. the local
scope inside the function loc() and global scope
outside the function loc(). Noornilo Nafees 45
 Points to remember:
 Functions are named blocks of code that are designed to do
one specific job.
 Types of Functions are User defined, Built-in, lambda and
recursion.
 Function blocks begin with the keyword “def ” followed by
function name and parenthesis ().
 A “return” with no arguments is the same as return None.
 Return statement is optional in python.
 In Python, statements in a block should begin with
indentation.
 A block within a block is called nested block.
 Arguments are used to call a function and there are
primarily 4 types of functions that one can use: Required
arguments, Keyword arguments, Default arguments and
Variable-length arguments. Noornilo Nafees 46
 Required arguments are the arguments passed to a
function in correct positional order.
 Keyword arguments will invoke the function after the

parameters are recognized by their parameter


names.
 A Python function allows to give the default values

for parameters in the function definition. We call it


as Default argument.
 Variable-Length arguments are not specified in the

function’s definition and an asterisk (*) is used to


define such arguments.
 Anonymous Function is a function that is defined

without a name.
Noornilo Nafees 47
 Scope of variable refers to the part of the program,
where it is accessible, i.e., area where you can refer
(use) it.
 The value returned by a function may be used as an

argument for another function in a nested manner.


This is called composition.
 A function which calls itself is known as recursion.

Noornilo Nafees 48
 Module 3 Quiz:
 A named blocks of code that are designed to do one specific job is called as
 (a) Loop (b) Branching
 (c) Function (d) Block
 2. A Function which calls itself is called as
 (a) Built-in (b) Recursion
 (c) Lambda (d) return
 3. Which function is called anonymous un-named function
 (a) Lambda (b) Recursion
 (c) Function (d) define
 4. Which of the following keyword is used to begin the function block?
 (a) define (b) for
 (c) finally (d) def
 5. Which of the following keyword is used to exit a function block?
 (a) define (b) return
 (c) finally (d) def
 6. While defining a function which of the following symbol is used.
 (a) ; (semicolon) (b) . (dot)
 (c) : (colon) (d) $ (dollar) Noornilo Nafees 49
 7. In which arguments the correct positional order is passed to a
function?
 (a) Required (b) Keyword
 (c) Default (d) Variable-length
 8. Read the following statement and choose the correct statement(s).
 (I) In Python, you don’t have to mention the specific data types while
defining
 function.
 (II) Python keywords can be used as function name.
 (a) I is correct and II is wrong
 (b) Both are correct
 (c) I is wrong and II is correct
 (d) Both are wrong
 9. Pick the correct one to execute the given statement successfully.
 if ____ : print(x, " is a leap year")
 (a) x%2=0 (b) x%4==0
 (c) x/4=0 (d) None of the above
Noornilo Nafees 50
 Which of the following keyword is used to define the
function testpython(): ?
 (a) define (b) pass
 (c) def (d) while

Noornilo Nafees 51
 Hands on:
 1. Evaluate the following functions and write the

output.
 1. eval(‘25*2-5*4')
 2. math.sqrt(abs(-81))
 3. math.ceil(3.5+4.6)
 4. math.floor(3.5+4.6)

Noornilo Nafees 52
 2. Valuate the following functions and write the output.
 1) abs(-25+12.0))
 2) abs(-3.2)
 3) ord('2')
 4) ord('$')
 5) type('s')
 6) bin(16)
 7) chr(13)
 8) print(chr(13))
 9) round(18.2,1)
 10) round(18.2,0)
 11) round(0.5100,3)
 12) round(0.5120,3)

Noornilo Nafees 53
 3. Valuate the following functions and write the output.
 1)format(66, 'c')
 2) format(10, 'x')
 3) format(10, 'X')
 4) format(0b110, 'd')
 5) format(0xa, 'd')
 4. Valuate the following functions and write the output.
 1) pow(2,-3)
 2) pow(2,3.0)
 3) pow(2,0)
 4) pow((1+2),2)
 5) pow(-3,2)
 6) pow(2*2,2)
Noornilo Nafees 54

You might also like