CHAPTER 3 : Functions in Python
• Function is a named sequence of statements used to
perform specific task when it is invoked.
• Functions may or may not return value. It contains
statements, which are sequentially executed from top to
bottom by python Interpreter.
• Once defined, a function can be called repeatedly from
different places of the program without writing same
code of that function every time, or it can be called
from inside another function, by simply writing the name
of the function and passing the required parameters, if
any
Advantages of Using a Function
*1) Use of functions enhances the
readability of a program.
*2) A big code is always difficult to read.
Breaking the code in smaller parts called
Functions, keeps the program organized,
easy to understand and makes it reusable
*3) Functions are used to achieve
modularity and reusability.
• Functions can be categorized in three
types-
1. Built-in
2. Modules
3. User Defined
Built-in Functions
• These are the functions which are
predefined in python we have to just call them
to use.
• Functions make any programming
language efficient and provide a structure to
language.
• Python has many built-in functions
which makes programming easy, fast and
efficient.
• They always reside in standard library and we
need not to import any module to use them.
•
Built-in Functions.
. .
1. Type Conversion Functions: These are
the functions which converts the values from one type to
another-
1. int( ) – To convert the string into integer.
2. str( ) – To covert any value into string.
3. float( ) – To covert string into float.
2. Input Functions: This function is used to take input from
user.
e.g. i) name=input(“Enter your name : “)
ii) n= int(input(‘Enter number:’))
3. eval function: This function is used to evaluate the value
of a string.
e.g. x=eval(“10+10“)
print(x) # answer will be
Built-in Functions.
. .
4. min Function: This
function returns the smallest
value among given list of
values.
5. max Function: This
bigges
t
function returns
the value among
given
list
of
values.
6. abs Function: This
function returns the absolute
value of any integer which is
always positive.
Built-in Functions.
. .
7.type Function: This
function is used to identify the
type of any value or variable.
8.len Function: This
function returns the length of
given string.
9.round Function: This
function returns the rounded
number of given number up to
given position.
Built-in Functions.
. .
10. range Function: If
you want the series between
two numbers then you can use
this function. This is good tool
for FOR Loop. Its syntax is -
range( start, stop, step)
This gives the series from
START to STOP-1 and the
interval between two numbers
of series will be STEP.
cmp( x, y ) It returns the sign of
the
difference of two
numbers:
-1 if x < y, 0 if x == y,
or 1
if x > y, where x and y
are
numeric
variable/expression.
>>>cmp(80, 100)
-1
>>>cmp(180, 100)
1
>>>cmp(80,80)
0
divmod (x,y ) Returns both quotient
and
remainder by division
through a tuple, when
x is
divided by y; where x
& y
are
variable/expression.
>>> divmod (10,5)
(2,0)
math.fabs(x) absolute value of x
x may be an integer or
floating point number
>>> math.fabs(6.7)
6.7
>>> math.fabs(-6.7)
6.7
>>> math.fabs(-4)
4.0
math.factorial(x) factorial of x where x is
positive integer
>>> math.factorial(0)
1
>>>math.factorial(3)
6
math.fmod(x,y) x % y with sign of x
x and y may be an
integer or floating point
number
>>> math.fmod(4,4.9)
4.0
>>> math.fmod(4.9,4.9)
0.0
>>> math.fmod(-4.9,2.5)
-2.4
>>> math.fmod(4.9,-4.9)
0.0
math.gcd(x,y) gcd (greatest common
divisor) of x and y
x, y are positive integers
>>> math.gcd(12,15)
3
Python Modules
• Module is a .py file which contains the definitions
of functions and variables.
• When we divide a program into modules then
each module contains functions and variables.
And each functions is made for a special task.
• Once written code in modules can be used in
other programs.
• When we make such functions which may be
used in other programs also, then we write them
in module.
We can import those module in any program.
Python Modules..
.
of import
• Python provides two ways
• import statement: to import full module.
• from: To import all or selected functions from the module.
Math Module
• math module contains following
functions–
– ceil(x) returns integer bigger than x or x integer.
– floor(x) returns integer smaller than x or x integer.
– pow(x, n) returns xn.
– sqrt(x) returns square root of x.
– log10(x) returns logarithm of x with base-10
– cos(x) returns cosine of x in radians.
– sin(x) returns sine of x in radians.
– tan(x) returns tangent of x in radians.
Random Module
• When we require random numbers to be generated.
e.g. captcha or any type of serial numbers then in this
situation we need random numbers. And here random module
helps us. This contains following functions-
• randrange (): This method always returns any integer between given
lower and upper limit to this method. default lower value is zero (0) and
upper value is one(1).
• random (): This generates floating value between 0 and 1. it does not
require any argument.
Random
Module. . .
• randint (): This method takes 2 parameters a,b in which first one is lower
and second is upper limit. This may return any number between these two
numbers including both limits. This method is very useful for guessing
applications.
• uniform (): This method return any floating-point number between
two given numbers.
String Module
– String.capitalize() Converts first character to Capital Letter
– String.find() Returns the Lowest Index of Substring
– String.index() Returns Index of Substring
– String.isalnum() Checks Alphanumeric Character
– String.isalpha() Checks if All Characters are Alphabets
– String.isdigit() Checks Digit Characters
– String.islower() Checks if all Alphabets in a String, are
Lowercase
– String.isupper() returns if all characters are uppercase
characters
– String.join() Returns a Concatenated String
– String.lower() returns lowercased string
– String.upper()returns uppercased string
– len()Returns Length of an Object
– ord()returns Unicode code point for Unicode character
– reversed()returns reversed iterator of a sequence
– slice()creates a slice object specified by range()
*Module name : statistics
This module provides functions for calculating statistics of
numeric (Real-valued) data. It can be included in the program
by using the following statements:
*import statistics
Function syntax Argument Return Example
Output
statistics.mean(x) x is a numeric
sequence
arithmetic
mean
>>> statistics.
mean([11,24,32,45,51])
32.6
statistics.median(x) x is a numeric
sequence
median
(middle
value) of x
>>>statistics.
median([11,24,32,45,51])
32
statistics.mode(x) x is a sequence mode
(the most
repeated
value)
>>> statistics.
mode([11,24,11,45,11])
11
>>> statistics.
mode(("red","blue","red"))
'red'
User-defined Functions
• These are the functions which are made by
user as per the requirement of the user.
• We can use them in any part of our
program by calling them.
• def keyword is used to make user defined
functions.
User-defined Functions. .
.
• We use following syntax with def
keyword to prepare a user defined function.
def Function_Name(List_Of_Parameters):
”””docstring”””
statement(s)
Keyword
Function
Definition
After the line containing def
there should be a 4 spaces
indentation, which is also
know as the body or block
of the function.
User-defined Functions without argument and without return
Function
Definition
Function Call
User-defined Functions with argument and without return
In the case of arguments,
the values are passed in the
function’s parenthesis. And
they are declared in
definition as well.
User-defined Functions with argument
and with return value
In the case of returning
value, the calculated value is
sent outside the function by
a returning statement. This
returned value will be hold
by a variable used in calling
statement.
User-defined Functions with multiple
return values
In pytho
n
may return
a
function
multiple
values. In multiple
returning it returns a
sequence of values to
the calling statement.
These returned values
may be used as per the
requirement.
User-defined Functions with multiple return values
Last program may also
be written as follows.
Result will be the tuple
here.
Parameters and Arguments in Functions
• When we write header of any function then the
one or more values given to its parenthesis ( )
are known as parameter.
• These are the values which are used by the
function for any specific task.
• While argument is the value passed at the time
of calling a function.
• In other words the arguments are used to
invoke a function.
• Formal parameters are said to be parameters
and actual parameters are said to be
arguments.
These are the parameters .
These are the arguments .
Parameters and Arguments in
Functions . . .
Neha Tyagi, PGT CS, KV No-5,Jaipur
Types of Arguments
• Python supports 4 types of
arguments-
1. Positional Arguments
2. Default Arguments
3. Keyword Arguments
4. Variable Length Arguments
1. Positional Arguments
• These are the arguments
which are passed in correct
positional order in function.
• If we change the position of the
arguments then the answer
will be changed.
2. Default
Arguments
• A default value is a value that is
predefined and assigned to the parameter
when the function call does not have its
corresponding argument.
Write python code to find simple interest.
3. Keyword Arguments
• If a function have many arguments and we want to
change the sequence of them then we have to
use keyword arguments.
• Biggest benefit of keyword argument is that
we need not to remember the position of the
argument.
• For this whenever we pass the values to the
function then we pass the values with the
argument name.
Neha Tyagi, PGT CS, KV No-5,Jaipur
4. Variable Length Arguments
• As we can assume by the name that we can pass any number of
arguments according to the requirement. Such arguments are
known as variable length arguments.
• We use (*) asterik to give Variable length argument.
You can notice here
that every time the
number of arguments
are different and the
answer is calculated
for each number of
arguments.
Passing ARRAYS / LISTS to Function
• In python we use list as array. Well we have to import numpy
module to use array in python.
• We will pass here list to the function. As we know that
list is better than array.
Write python code to print average of list elements
def list_avg(li):
sum=0
for i in li:
sum=sum+i
return sum/n
li=[]
n=int(input('Enter size of elements to be enter in list:'))
c=0
while c<n:
a=int(input('Enter numbers in list:'))
li.append(a)
c=c+1
print(li)
avg1=list_avg(li)
print('Average of list is;',round(avg1,2))
*Output is
Enter size of elements to be enter in
list:4
Enter numbers in list:34
Enter numbers in list:5
Enter numbers in list:23
Enter numbers in list:56
[34, 5, 23, 56]
Average of list is; 29.5
Scope of Variable
• Scope of variable means the part of program where
the variable will be visible. It means where we can
use this variable.
• We can say that scope is the collection of variables
and their values.
• Scope can of two types -
• Global (module)
– All those names which are assigned at top level in module
or directly assigned in interpreter.
• Local (function)
– Those variables which are assigned within a loop of
function.
Global Variable Local variable
1) A variable that has global scope
is known as global variable
1) A variable that has local scope is
known as local variable
2) a variable that is defined
outside any function or any block
is known as a global variable
2) A variable that is defined inside
any function or a block
is known as a local variable
3) It can be accessed throughout
the python code
3) It can be accessed only in
the function or a block where it is
defined.
4) Any change made to the global
variable will impact all the
functions in the program where
that variable can be accessed.
4) Any change made to the local
variable will not impact all the
functions in the program where
that variable can be accessed.
5) It exists throughout the
program
5) It exists only till the function
executes.
Difference between Global variable and local variable
Using main() as a Function
• Main function is not necessary in python.
• For the convenience of Non-python programmers, we
can use it as follows-
Write flow of execution of following python code.
1->7->8->9->1->2->3->4->9->10->11->12->13->1->2->3->4->14->15->16
ANSWER IS:
1. def increment(x):
2. z=45
3. x=x+1
4. return x
5.
6. #main
7. y=3
8. print(y)
9. y=increment(y)
10. print(y)
11. q=77
12. print(q)
13. increment(q)
14. print(q)
15. print(x)
16. print(z)
RECURSION
• In recursion, function calls itself until
the condition is not satisfied.
RECURSION. . .
• Recursion is one of the most powerful tools of the
programming language. When a function calls itself
within its body then this is know as recursion.
• There are two conditions to use recursion -
– There must be a terminating condition.
– There must be if condition in recursive routine.
– Every recursive problem has a special feature its
reversal in the order of execution.
– As many times there is recursive call then every
time a new memory is allocated to the local
variables of recursive function.
– During recursion each value is pushed in a stack.
Drawbacks of RECURSION
•It uses more storage as each values is
pushed in to stack.
•If recursive call is not checked
carefully then your computer may go out
of memory.
•It is less efficient in terms of time and
speed.
*Write python code to find factorial of a number using recursion
def fact (n):
if n==0:
return 1
else:
return n*fact(n-1)
n=int(input('Enter no:'))
x=fact(n)
print('Factorial is:',x)

function_xii-BY APARNA DENDRE (1).pdf.pptx

  • 1.
    CHAPTER 3 :Functions in Python • Function is a named sequence of statements used to perform specific task when it is invoked. • Functions may or may not return value. It contains statements, which are sequentially executed from top to bottom by python Interpreter. • Once defined, a function can be called repeatedly from different places of the program without writing same code of that function every time, or it can be called from inside another function, by simply writing the name of the function and passing the required parameters, if any
  • 2.
    Advantages of Usinga Function *1) Use of functions enhances the readability of a program. *2) A big code is always difficult to read. Breaking the code in smaller parts called Functions, keeps the program organized, easy to understand and makes it reusable *3) Functions are used to achieve modularity and reusability.
  • 3.
    • Functions canbe categorized in three types- 1. Built-in 2. Modules 3. User Defined
  • 4.
    Built-in Functions • Theseare the functions which are predefined in python we have to just call them to use. • Functions make any programming language efficient and provide a structure to language. • Python has many built-in functions which makes programming easy, fast and efficient. • They always reside in standard library and we need not to import any module to use them. •
  • 5.
    Built-in Functions. . . 1.Type Conversion Functions: These are the functions which converts the values from one type to another- 1. int( ) – To convert the string into integer. 2. str( ) – To covert any value into string. 3. float( ) – To covert string into float. 2. Input Functions: This function is used to take input from user. e.g. i) name=input(“Enter your name : “) ii) n= int(input(‘Enter number:’)) 3. eval function: This function is used to evaluate the value of a string. e.g. x=eval(“10+10“) print(x) # answer will be
  • 6.
    Built-in Functions. . . 4.min Function: This function returns the smallest value among given list of values. 5. max Function: This bigges t function returns the value among given list of values. 6. abs Function: This function returns the absolute value of any integer which is always positive.
  • 7.
    Built-in Functions. . . 7.typeFunction: This function is used to identify the type of any value or variable. 8.len Function: This function returns the length of given string. 9.round Function: This function returns the rounded number of given number up to given position.
  • 8.
    Built-in Functions. . . 10.range Function: If you want the series between two numbers then you can use this function. This is good tool for FOR Loop. Its syntax is - range( start, stop, step) This gives the series from START to STOP-1 and the interval between two numbers of series will be STEP.
  • 9.
    cmp( x, y) It returns the sign of the difference of two numbers: -1 if x < y, 0 if x == y, or 1 if x > y, where x and y are numeric variable/expression. >>>cmp(80, 100) -1 >>>cmp(180, 100) 1 >>>cmp(80,80) 0 divmod (x,y ) Returns both quotient and remainder by division through a tuple, when x is divided by y; where x & y are variable/expression. >>> divmod (10,5) (2,0)
  • 10.
    math.fabs(x) absolute valueof x x may be an integer or floating point number >>> math.fabs(6.7) 6.7 >>> math.fabs(-6.7) 6.7 >>> math.fabs(-4) 4.0 math.factorial(x) factorial of x where x is positive integer >>> math.factorial(0) 1 >>>math.factorial(3) 6 math.fmod(x,y) x % y with sign of x x and y may be an integer or floating point number >>> math.fmod(4,4.9) 4.0 >>> math.fmod(4.9,4.9) 0.0 >>> math.fmod(-4.9,2.5) -2.4 >>> math.fmod(4.9,-4.9) 0.0 math.gcd(x,y) gcd (greatest common divisor) of x and y x, y are positive integers >>> math.gcd(12,15) 3
  • 11.
    Python Modules • Moduleis a .py file which contains the definitions of functions and variables. • When we divide a program into modules then each module contains functions and variables. And each functions is made for a special task. • Once written code in modules can be used in other programs. • When we make such functions which may be used in other programs also, then we write them in module. We can import those module in any program.
  • 12.
    Python Modules.. . of import •Python provides two ways • import statement: to import full module. • from: To import all or selected functions from the module.
  • 13.
    Math Module • mathmodule contains following functions– – ceil(x) returns integer bigger than x or x integer. – floor(x) returns integer smaller than x or x integer. – pow(x, n) returns xn. – sqrt(x) returns square root of x. – log10(x) returns logarithm of x with base-10 – cos(x) returns cosine of x in radians. – sin(x) returns sine of x in radians. – tan(x) returns tangent of x in radians.
  • 14.
    Random Module • Whenwe require random numbers to be generated. e.g. captcha or any type of serial numbers then in this situation we need random numbers. And here random module helps us. This contains following functions- • randrange (): This method always returns any integer between given lower and upper limit to this method. default lower value is zero (0) and upper value is one(1). • random (): This generates floating value between 0 and 1. it does not require any argument.
  • 15.
    Random Module. . . •randint (): This method takes 2 parameters a,b in which first one is lower and second is upper limit. This may return any number between these two numbers including both limits. This method is very useful for guessing applications. • uniform (): This method return any floating-point number between two given numbers.
  • 16.
    String Module – String.capitalize()Converts first character to Capital Letter – String.find() Returns the Lowest Index of Substring – String.index() Returns Index of Substring – String.isalnum() Checks Alphanumeric Character – String.isalpha() Checks if All Characters are Alphabets – String.isdigit() Checks Digit Characters – String.islower() Checks if all Alphabets in a String, are Lowercase – String.isupper() returns if all characters are uppercase characters – String.join() Returns a Concatenated String – String.lower() returns lowercased string – String.upper()returns uppercased string – len()Returns Length of an Object – ord()returns Unicode code point for Unicode character – reversed()returns reversed iterator of a sequence – slice()creates a slice object specified by range()
  • 17.
    *Module name :statistics This module provides functions for calculating statistics of numeric (Real-valued) data. It can be included in the program by using the following statements: *import statistics Function syntax Argument Return Example Output statistics.mean(x) x is a numeric sequence arithmetic mean >>> statistics. mean([11,24,32,45,51]) 32.6 statistics.median(x) x is a numeric sequence median (middle value) of x >>>statistics. median([11,24,32,45,51]) 32 statistics.mode(x) x is a sequence mode (the most repeated value) >>> statistics. mode([11,24,11,45,11]) 11 >>> statistics. mode(("red","blue","red")) 'red'
  • 18.
    User-defined Functions • Theseare the functions which are made by user as per the requirement of the user. • We can use them in any part of our program by calling them. • def keyword is used to make user defined functions.
  • 19.
    User-defined Functions. . . •We use following syntax with def keyword to prepare a user defined function. def Function_Name(List_Of_Parameters): ”””docstring””” statement(s) Keyword Function Definition After the line containing def there should be a 4 spaces indentation, which is also know as the body or block of the function.
  • 20.
    User-defined Functions withoutargument and without return Function Definition Function Call
  • 21.
    User-defined Functions withargument and without return In the case of arguments, the values are passed in the function’s parenthesis. And they are declared in definition as well.
  • 22.
    User-defined Functions withargument and with return value In the case of returning value, the calculated value is sent outside the function by a returning statement. This returned value will be hold by a variable used in calling statement.
  • 23.
    User-defined Functions withmultiple return values In pytho n may return a function multiple values. In multiple returning it returns a sequence of values to the calling statement. These returned values may be used as per the requirement.
  • 24.
    User-defined Functions withmultiple return values Last program may also be written as follows. Result will be the tuple here.
  • 25.
    Parameters and Argumentsin Functions • When we write header of any function then the one or more values given to its parenthesis ( ) are known as parameter. • These are the values which are used by the function for any specific task. • While argument is the value passed at the time of calling a function. • In other words the arguments are used to invoke a function. • Formal parameters are said to be parameters and actual parameters are said to be arguments.
  • 26.
    These are theparameters . These are the arguments . Parameters and Arguments in Functions . . .
  • 27.
    Neha Tyagi, PGTCS, KV No-5,Jaipur Types of Arguments • Python supports 4 types of arguments- 1. Positional Arguments 2. Default Arguments 3. Keyword Arguments 4. Variable Length Arguments
  • 28.
    1. Positional Arguments •These are the arguments which are passed in correct positional order in function. • If we change the position of the arguments then the answer will be changed.
  • 29.
    2. Default Arguments • Adefault value is a value that is predefined and assigned to the parameter when the function call does not have its corresponding argument. Write python code to find simple interest.
  • 30.
    3. Keyword Arguments •If a function have many arguments and we want to change the sequence of them then we have to use keyword arguments. • Biggest benefit of keyword argument is that we need not to remember the position of the argument. • For this whenever we pass the values to the function then we pass the values with the argument name.
  • 31.
    Neha Tyagi, PGTCS, KV No-5,Jaipur 4. Variable Length Arguments • As we can assume by the name that we can pass any number of arguments according to the requirement. Such arguments are known as variable length arguments. • We use (*) asterik to give Variable length argument. You can notice here that every time the number of arguments are different and the answer is calculated for each number of arguments.
  • 32.
    Passing ARRAYS /LISTS to Function • In python we use list as array. Well we have to import numpy module to use array in python. • We will pass here list to the function. As we know that list is better than array.
  • 33.
    Write python codeto print average of list elements def list_avg(li): sum=0 for i in li: sum=sum+i return sum/n li=[] n=int(input('Enter size of elements to be enter in list:')) c=0 while c<n: a=int(input('Enter numbers in list:')) li.append(a) c=c+1 print(li) avg1=list_avg(li) print('Average of list is;',round(avg1,2))
  • 34.
    *Output is Enter sizeof elements to be enter in list:4 Enter numbers in list:34 Enter numbers in list:5 Enter numbers in list:23 Enter numbers in list:56 [34, 5, 23, 56] Average of list is; 29.5
  • 35.
    Scope of Variable •Scope of variable means the part of program where the variable will be visible. It means where we can use this variable. • We can say that scope is the collection of variables and their values. • Scope can of two types - • Global (module) – All those names which are assigned at top level in module or directly assigned in interpreter. • Local (function) – Those variables which are assigned within a loop of function.
  • 36.
    Global Variable Localvariable 1) A variable that has global scope is known as global variable 1) A variable that has local scope is known as local variable 2) a variable that is defined outside any function or any block is known as a global variable 2) A variable that is defined inside any function or a block is known as a local variable 3) It can be accessed throughout the python code 3) It can be accessed only in the function or a block where it is defined. 4) Any change made to the global variable will impact all the functions in the program where that variable can be accessed. 4) Any change made to the local variable will not impact all the functions in the program where that variable can be accessed. 5) It exists throughout the program 5) It exists only till the function executes. Difference between Global variable and local variable
  • 38.
    Using main() asa Function • Main function is not necessary in python. • For the convenience of Non-python programmers, we can use it as follows-
  • 39.
    Write flow ofexecution of following python code. 1->7->8->9->1->2->3->4->9->10->11->12->13->1->2->3->4->14->15->16 ANSWER IS: 1. def increment(x): 2. z=45 3. x=x+1 4. return x 5. 6. #main 7. y=3 8. print(y) 9. y=increment(y) 10. print(y) 11. q=77 12. print(q) 13. increment(q) 14. print(q) 15. print(x) 16. print(z)
  • 40.
    RECURSION • In recursion,function calls itself until the condition is not satisfied.
  • 41.
    RECURSION. . . •Recursion is one of the most powerful tools of the programming language. When a function calls itself within its body then this is know as recursion. • There are two conditions to use recursion - – There must be a terminating condition. – There must be if condition in recursive routine. – Every recursive problem has a special feature its reversal in the order of execution. – As many times there is recursive call then every time a new memory is allocated to the local variables of recursive function. – During recursion each value is pushed in a stack.
  • 42.
    Drawbacks of RECURSION •Ituses more storage as each values is pushed in to stack. •If recursive call is not checked carefully then your computer may go out of memory. •It is less efficient in terms of time and speed.
  • 43.
    *Write python codeto find factorial of a number using recursion def fact (n): if n==0: return 1 else: return n*fact(n-1) n=int(input('Enter no:')) x=fact(n) print('Factorial is:',x)