Unit 4 Functions
Unit 4 Functions
UNIT -4
FUNCTIONS:
A function is a block of code which only runs when it is called. A function in any programming
language is a sequence of statements in a certain order, given a name. When called, those statements
are executed. So we don’t have to write the code again and again for each Time. This is called code
re-usability
Once a function is written, it can be reused when it is required. So, functions are also
called reusable code.
Functions provide modularity for programming. A module represents a part of the
program. Usually, a programmer divides the main task into smaller sub tasks called
modules.
Code maintenance will become easy because of functions. When a new feature has to be
added to the existing software, a new function can be written and integrated into the
software.
When there is an error in the software, the corresponding function can be modified without
disturbing the other functions in the software.
The use of functions in a program will reduce the length of the program.
The use of functions in a program will reduce the length of the program. As you already
know, Python gives you many built-in functions like sqrt( ), etc. but you can also create
your own functions. These functions are called user-defined functions.
Defining a Function
You can define functions to provide the required functionality. Here are simple rules to define a
function in Python.
Function blocks begin with the keyword def followed by the function name and
parentheses ( ).
Any input parameters or arguments should be placed within these parentheses. You can
also define parameters inside these parentheses.
The code block within every function starts with a colon (:) and is indented. Optional
documentation string (docstring) to describe what the function does.
Syntax of Function:
def function_name(parameters):
"""docstring"""
statement(s)
Example:
def sri():
print(“hello sri”)
output:
Example:
def add(a,b):
"""This function sum the numbers"""
c=a+b
print( c)
output:
Here, def represents starting of function. add is function name. After this name, parentheses ( )
are compulsory as they denote that it is a function and not a variable or something else. In the
parentheses we wrote two variables a and b these variables are called parameters A parameter is a
variable that receives data from outside a function. So, this function receives two values from
outside and those are stored in the variables a and b. After parentheses, we put colon (:)
Calling Function:
A function cannot run by its own. It runs only when we call it. So, the next step is to call function
using its name. While calling the function, we should pass the necessary values
to the function in the parentheses as:
Example:
def add(a,b):
"""This function sum the numbers"""
c=a+b
print(c)
add(48,12)
output:
Here, we are calling add function and passing two values 48 and 12 to that function. When this
statement is executed, the python interpreter jumps to the function definition and copies the values
48 and 12 into the parameters a and b respectively.
Example:
def sri():
print("hai srikanth")
sri()
sri()
sri()
output:
Passing Arguments:
When the function call statement must match the number and order of arguments as defined in the
function definition. It is Positional Argument matching.
Example:
def sum(a,b):
"Function having two parameters"
c=a+b
print(c)
sum(10,20)
sum(20)
output:
Example:
def attach(s1,s2):
s3=s1+s2
print(s3)
attach("MIC","CSE") #Positional arguments
output:
Parameters:
Example:
def my_function(fname):
print(fname + " MIC CSE ")
my_function("srikanth")
my_function("jvs")
my_function("kalyan")
my_function("TKC")
output:
Alternatively, arguments can be called as actual parameters or actual arguments and parameters
can be called as formal parameters or formal arguments.
Example:
def addition(x,y):
print(x+y)
x=15
addition(x ,10)
addition(x,x)
y=20
addition(x,y)
output:
Keyword Arguments:
Keyword arguments are arguments that identify the parameters by their names. Using the
Keyword Argument, the argument passed in function call is matched with function definition on
the basis of the name of the parameter.
For example, the definition of a function that displays grocery item and its price can be written as:
grocery(item=’sugar’, price=50.75)
Here, we are mentioning a keyword item and its value and then another keyword price and its
value. Please observe these keywords are nothing but the parameter names which receive these
values. We can change the order of the arguments as:
grocery(price=88.00, item=’oil’)
In this way, even though we change the order of the arguments, there will not be any problem
as the parameter names will guide where to store that value.
Example:
def grocery(item,price):
print("item=",item)
print("price=",price)
grocery(item="sugar",price=50.75) # keyword arguments
grocery(price=88.00,item="oil") # keyword arguments
output:
output:
Default Arguments:
We can mention some default value for the function parameters in the definition. Let’s take the
definition of grocery( ) function as:
Example:
def grocery(item,price=40.00):
print("item=",item)
print("price=",price)
grocery(item="sugar",price=50.75)
grocery(item="oil")
grocery(item="pen")
output:
Example:
def msg(Id,Name,Age=21,College="MIC"):
print(Id,Name,Age,College)
msg(Id=100,Name='srikanth',Age=27)
msg(Id=101,Name='ramsat')
msg(Id=102,Name='vinode')
output:
Example:
def clg(college="MIC"):
print("my college " + college)
clg()
clg("J.N.T.U.K")
clg("VRSE")
clg()
output:
But, the user who is using this function may want to use this function to find sum of three
numbers. In that case, there is a chance that the user may provide 3 arguments to this function
as: add(10,15,20)
Then the add( ) function will fail and error will be displayed. If the programmer want to develop a
function that can accept n arguments, that is also possible in python. For this purpose, a variable
length argument is used in the function definition. a variable length argument is an argument that
can accept any number of values. The variable length argument is written with a * symbol before
it in the function definition as:
def add(farg, *args):
here, farg is the formal argument and *args represents variable length argument. We can pass 1 or
more values to this *args and it will store them all in a tuple.
Example:
def add(farg,*args):
sum=0
for i in args:
sum=sum+i
print("sum is",sum + farg)
add(5)
add(5,10)
add(5,10,20)
add(5,10,20,30)
add(5,10,20,30,40)
output:
Lambda functions can have any number of arguments but only one expression. The expression is
evaluated and returned.
if we want to make a function which will calculate sum of two number. The following code
Example:
def sum ( a, b ):
return a+b
print (sum(1, 2))
print (sum(3, 5))
output:
But, we can convert this function to anonymous function. The code will be like this
Example:
sum = lambda a,b: (a+b)
print(sum(1,2))
print(sum(3,5))
output:
Example:
x = lambda a: a + 10
print(x(5))
output: 15
A lambda function that multiplies argument a with argument b and print the result:
Example:
x = lambda a, b: a * b
print(x(5, 6))
output: 30
A lambda function that sums argument a, b, and c and print the result:
Example:
x = lambda a, b, c: a + b + c
print(x(5, 6, 2))
output: 13
output:
output:
Example:
def my_function(x):
return 5 * x
print(my_function(3))
print(my_function(5))
print(my_function(9))
output:
Example: program to find the sum of two numbers and return the result from the function.
def add(a,b):
"""This function sum the numbers"""
c=a+b
return c
print(add(48,12))
print(add(48,58))
output:
A function can returns a single value in the programming languages like C, C++ and JAVA. But,
in python, a function can return multiple values. When a function calculates multiple results and
wants to return the results, we can use return statement as: return a, b, c
Here, three values which are in a, b and c are returned. These values are returned by the function
as a tuple. To take these values, we can three variables at the time of calling the function as:
x, y, z = functionName( )
Here x, y and z are receiving the three values returned by the function.
Example:
def calc(a,b):
c=a+b
d=a-b
e=a*b
return c,d,e
x,y,z=calc(5,8)
print ("Addition=",x)
print ("Subtraction=",y)
print ("Multiplication=",z)
output:
There are two types of variables: global variables and local variables. A global variable can be
reached anywhere in the code, a local only in the scope.
Variables can only reach the area in which they are defined, which is called scope.
A global variable (x) can be reached and modified anywhere in the code, local variable (z) exists
only in block 3.
Local Variables: When we declare a variable inside a function, it becomes a local variable. A
local variable is a variable whose scope is limited only to that function where it is created. That
means the local variable value is available only in that function and not outside of that function.
When the variable a is declared inside myfunction() and hence it is available inside that function.
Once we come out of the function, the variable a is removed from memory and it is not
available.
output:
output:
Global Variables: In Python, a variable declared outside of the function or in global scope is
known as global variable. This means, global variable can be accessed inside or outside of the
function.
Example : Create a Global Variable:
x = "global"
def sri():
print("x inside :", x)
sri()
print("x outside:", x)
output:
Example :
a=2
def myfunction():
b=48
print("Inside function",a) #display global var
print("Inside function",b) #display local var
myfunction()
print("outside function",a) # available
print("outside function",b) # error
output:
This is because we can only access the global variable but cannot modify it from inside the
function. The solution for this is to use the global keyword.
Example:
c = 0 # global variable
def add():
global c
c = c + 2 # increment by 2
print("Inside add():", c)
add()
print("In main:", c)
output:
Inside add(): 2
In main: 2
Example:
a=21
def myfunction():
global a
a=20
print("Inside function",a) # display global variable
myfunction()
print("outside function",a) # display global variable
output:
Recursive Function:
A function that calls itself is known as „recursive function‟. For example, we can write the
factorial of 3 as:
factorial(3) = 3 * factorial(2)
Here, factorial(2) = 2 * factorial(1)
And, factorial(1) = 1 * factorial(0)
Now, if we know that the factorial(0) value is 1, all the preceding statements will evaluate
and give the result as:
factorial(3) = 3 * factorial(2)
= 3 * 2 * factorial(1)
= 3 * 2 * 1 * factorial(0)
=3*2*1*1
=6
From the above statements, we can write the formula to calculate factorial of any number n
as: factorial(n) = n * factorial(n-1)
Example:
def factorial(n):
if n==0:
result=1
else:
result=n*factorial(n-1)
return result
for i in range(1,5):
print("factorial of ",i,"is",factorial(i))
output:
Modules
Modular programming refers to the process of breaking a large, unmanageable programming
task into separate, smaller, more manageable subtasks or modules. Individual modules can then
be combine together like building blocks to create a larger application.
It allows you to reuse one or more functions in your programs, even in the programs in which
those functions have not been defined.
Modules are pre-written pieces of code that are used to perform common tasks like generating
random numbers, performing mathematical operations, etc.
Create a Module:
Example: save this program func30
def greeting(name):
print("Hello, " + name)
Use a Module:
Now we can use the module we just created, by using the import statement:
Import the module named func30, and call the greeting function:
The module can contain functions, as already described, but also variables of all types (arrays,
dictionaries, objects etc):
Import in python is similar to #include header_file in C/C++. Python modules can get access to
code from another module by importing the file/function using import. The import statement is the
most common way of invoking the import machinery
Import module_name
When import is used, it searches for the module initially in the local scope by calling
__import__() function. The value returned by the function are then reflected in the output of the
initial code.
Import the module named func31, and access the college dictionary:
Re-naming a Module:
You can create an alias when you import a module, by using the as keyword:
Create an alias for func31 called sri:
You can choose to import only parts from a module, by using the from keyword. When you import a
module you can use any variable or function defined in the module
Example:
def greeting(name):
print("Hello, " + name)
person1 = {
name: "srikanth",
age: 27,
place: "vijayawada"
}
output:
Name spacing
Name (also called identifier) is simply a name given to objects. Everything in Python is an object.
Name is a way to access the underlying object.
A Python statement can access variables in a local namespace and in the global namespace. If a
local and a global variable have the same name, the local variable shadows the global variable.
Example:
#module1-----------func34.py
def repeat_x(x):
y= x*2
print(y)
#module2----------func35.py
def repeat_x(x):
y=x**2
print(y)
Python packages
pip is a tool for installing packages from the Python Package Index. pip is a package management
system used to install and manage software packages written in Python. Many packages can be
found in the default source for packages and their dependencies Python Package Index (PyPI).
The Python Package Index (PyPI) is a repository of software for the Python programming
language. PyPI helps you find and install software developed and shared by the Python
community
A package is a hierarchical file directory structure that defines a single Python application
environment that consists of modules and sub packages and sub subpackages, and so on.
The Python has got the greatest community for creating great python packages. There are more
tha 1,00,000 Packages available at https://pypi.python.org/pypi . Python Package is a collection of
all modules connected properly into one form and distributed PyPI, the Python Package Index
maintains the list of Python packages available.
Note: In windows, pip file is in “Python36\Scripts” folder. To install package you have goto
the path C:\Python36\Scripts in command prompt and install.
Verify a successful installation by opening a command prompt window and navigating to your
Python installation directory (default is C:\Python36). Type python from this location to launch
the Python interpreter.
when you are done with pip setup Go to command prompt / terminal and say
Pip install <package_name>
Pillow: A friendly fork of PIL (Python Imaging Library). It is more user-friendly than PIL and is a
must have for anyone who works with images.
Twisted: The most important tool for any network application developer.
SciPy: It is a library of algorithms and mathematical tools for python and has caused many
scientists to switch from ruby to python.
Matplotlib: It is a numerical plotting library. It is very useful for any data scientist or any data
analyzer.
plt.show()
output: