Functions in Python
Function is a collection of statements which is made to perform a
specific task.
• It is simply a group of statements under any name i.e. function name and can be invoked
(call) from other part of program.
• Set of functions is stored in a file called MODULE. And this approach is known as
MODULARIZATION,makes program easier to understand, test and maintain.
• Functions can be categorized in three types-
1. Built-in
Built in library
2. Modules
3. User Defined
Advantages of Function
PROGRAM HANDLING EASIER : only small part of the program is dealt with at a
time.
REDUCED LoC: as with function the common set of code is written only once and
can be called from any part ofprogram, so it reduces Line of Code
EASY UPDATING : if function is not used then set of code is to be repeated
everywhere it is required. Hence if we want to change in any formula/expression then
we have to make changes to every place, if forgotten then output will be not the desired
output. With function we have to make changes to only one location.
Built-in Functions
• These are the functions which are predefinedin python we have to just
call them to use.
• Python has many built-in functions whichmakes
programming easy, fast and efficient.
• They always reside in standard library and weneed not to import any
module to use them.
Built-in Functions
1. Type Conversion Functions:
These are thefunctions which converts the values from one type to another-
a. int( ) – To convert the string into integer.
b. str( ) – To covert any value into string.
c. float( ) – To covert string into float
2. Input Functions: This function is used to take input fromuser in the form of string.
• e.g. name=input(“Enter your name : “)
3. eval function: This function is used to evaluate the valueof a string.
• e.g. x=eval(“45+10“)
print(x)
min Function: This function returns the smallest value
among given list of values.
•max Function: This function returns the biggest
value among given list of values.
•abs Function: This function returns the absolute
value of any integer which is always positive.
type Function: This function is used to identify the type
of any value or variable.
•len Function: This function returns the length of given
string.
•round Function: This function returns the rounded
number of given number up to given position.
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.
Python Modules
• Module is a .py file which contains the definitions of functions and
variables.
• Library: It is a collection of one or more modules related to code.
• Package: A library/package is a folder containing all the modules it must
have a file named __init__.py to be considered and used as a library.
• Module is a simple python file.
• 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 an we can use the functions.
• Python provides two ways to import a module
import statement: to import full module.
from: To import all or selected functions from the module
math Module
• math module contains
followingfunctions–
– ceil(x) returns integer bigger than x or x integer.
– floor(x) returns integer smaller than x or x integer.
– pow(x, n) returns x . n
– 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.
help Function
•If you forgot that how a library function works then help( ) is very useful for this
situation.
•If this function is used with any module then it provides the information and details of
the given module and its all the contents.
string Module
• We have already studied about string module in class XI. Hereare some other functions
of 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
–
random Module
•When we require such numbers which are not known earlier 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).
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.
•random (): This generates floating
value between 0 and 1. it does not require
any argument.
uniform (): This method return any
floating-point number between two given
numbers.
choice (): this method is used for random selection from list, tuple or string.
shuffle (): this method can shuffle or swap the items of a given list.
USER-DEFINED FUNCTIONS
• These are the functions which are made by user as per the requirement of the user.
• def keyword is used to make user defined functions.
Functions are also known as sub-routine,methods, procedure or subprogram.
Function name must be unique and follows naming rulessame as for identifiers
Function can take arguments. It is optional
A colon(:) to mark the end of function header
Function can contains one or more statement to performspecific task
An optional return statement to return a value from thefunction.
Function must be called/invoked to execute its code
We can use them in any part of our program by calling them.
Syntax to create USER DEFINED FUNCTION
USER DEFINED FUNCTIONS CAN BE:
•Function with no arguments and no return
•Function with arguments but no return value
•Function with arguments and return value
•Function with no argument but return value
1 Function with no arguments and no return
Non returning functionis also known as VOID function
2 User-defined Functions with argument and
without return
User-defined Functions with argument and
without return
3. User-defined Functions with argument and
with return value
Return statement is used to return a value from a
function , it returns None by default
User-defined Functions with argument and
with return value
We can return values from function using return keyword.
The return value must be used at the calling placeby –
◼ Either store it any variable
◼ Use with print()
◼ Use in any expression
USER-DEFINED FUNCTIONS WITH MULTIPLE RETURN VALUES
Returning Multiple values
•Unlike other programming languages, python lets you
return more than one value from function.
•The multiple return value must be either stored in
TUPLE or we can UNPACK the received value by
specifying the same number of variables on the left of
assignment of function call.
•Let us see an example of both :-
Multiple return value stored in TUPLE
Multiple return value stored by
unpacking in multiple variables
USER-DEFINED FUNCTIONS WITH OUT ARGUMENTS WITH
RETURN
Parameters and Arguments in Functions
Parameters are the value(s) provided in the parenthesis when we write function
header. These are the valuesrequired by function to work
If there are more than one parameter, it must be separated by comma(,)
An Argument is a value that is passed to the function when it is called. In other words
arguments are the value(s) providedin function call/invoke statement
Parameter is also known as FORMAL ARGUMENTS/PARAMETERS
Arguments is also known as ACTUAL ARGUMENTS/PARAMETER
Note: Function can alter only MUTABLE TYPE values.
Types of Arguments
There are 4 types of Actual Arguments allowed inPython:
1. Positional arguments
2. Default arguments
3. Keyword 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
These are the arguments through which we can provide
default values to the function.
If we don’t pass any value to the function then it will take a pre
defined value.
Default argument must not followed by non-default arguments
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. e.g.
Rules for combining all three type of arguments
•An argument list must first contain positional arguments
followed by keyword arguments
•You cannot specify a value for an argument more than
once
Eg
def interest (p,r=4.5,t=2):
si=p*r*t/100
return si
Eg1 print(interest(2000,5,4))
Here p will be 20000, r will be taken as 5 and t will be 4.
Eg2 print(interest(3000,4))
Here p will be 30000, r will be taken as 4 and t will be 2. (t will take default value)
Eg3 print(interest(50000))
Here p will be 50000, r will be taken as 4 and t will be 2. (r,t will take default values)
Eg4 print(interest(5000, ,4))
Error: we cant skip from in between, values can be omitted only from the right hand
side.
def Average(n1,n2,n3=100):
return (n1+n2+n3)/3
FUNCTION CALL LEGAL/ ILLEGAL REASON
Average(n1=20, n2=40,n3=80) LEGAL Non default values provided asnamed
arguments
Average(n3=10,n2=7,n1=100) LEGAL Keyword argument can be in anyorder
Average(100,n2=10,n3=15) LEGAL Positional argument before thekeyword
arguments
Average(n3=70,n1=90,100) ILLEGAL Keyword argument before the
positional arguments
Average(100,n1=23,n2=1) ILLEGAL Multiple values provided for n1
Average(200,num2=90,n3=11 ILLEGAL Undefined argument NUM2
Average(200,n3=900) ILLEGAL N2 is missing
Scope of Variables
•SCOPE means in which part(s) of the program, a
particular piece of code or data is accessible or
known.
•In Python there are broadly 2 kinds of Scopes:
🞑 Global Scope
•A name declared in top level segment( main ) of a program is said to have global scope and can
be used in entire program.
•Variable defined outside all functions are global variables.
🞑 Local Scope
A name declare in a function body is said to have local scope i.e. it can be used only within this
function and the other block inside the function.
The formal parameters are also having local scope
„a‟ is not accessible
here because it is
declared in function
area(), so scope is
local to area()
Lifetime of Variable
•Is the time for which a variable lives in memory.
•For Global variables the lifetime is entire program run as long as
program is executing.
For Local variables lifetime is their function‟s run i.e. as long as
function is executing
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-
5
Flow of Execution at the Time of Function Call
• The execution of any program starts from the very first line andthis execution goes
line by line.
• One statement is executed at a time.
• Function doesn’t change the flow of any program.
• Statements of function doesn’t start executing until it is called.
• When function is called then the control is jumped into thebody of function.
• Then all the statements of the function gets executed from topto bottom one by
one.
• And again the control returns to the place where it was called.
And in this sequence the python program gets executed
Example: flow of execution
1. def greatest3(a,b,c):
6. if a>b and a>c:
7. return a
8. elif b>a and b>c:
9. return b
10. else:
11. return c
2. x=int(input(“enter first number”))
3.y=int(input(“enter second number”))
4.z=int(input(“enter third number”))
5. res=greatest3(x,y,z)
12. print(“greatest of three number is “,res)
Immutable Arguments
When integers ,floats , strings or tuples are passed to the functions as
parameters, that is said to be immutable arguments. The changes made to these
parameters are not reflected back in their respective arguments.
Eg
def change (n): Output
print(n) 15
n=n+10
print(n) 15
a=15 25
print(a) 15
change(a)
print(a)
• Changes made in n are not reflected back in a since it is integer and that is
immutable
• No return statement is used here, though we could retrieve the modified
value as a result
Passing Mutable Arguments
When list or dicionary is passed to the functions as parameters, The changes
made to these parameters are reflected back in their respective arguments.
Eg
def change (a):
for i in range(len(a)) Output
a[i]=a[i]+5
[10,20,30]
l=[10,20,30] [15,25,35]
print(l)
change(l)
print(l)
• Changes made in to the list are reflected back after the function call.