Sei sulla pagina 1di 22

Page 1

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.

Difference between a function and a method:


A function can be written individually in a python program. A function is called using its name.
When a function is written inside a class, it becomes a method. A method is called
using object name or class name.

A method is called using one of the following ways:


Objectname.methodname()
Classname.methodname()

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.

P.SRIKANTH DEPT OF CSE @MIC www.sristudy.in


Page 2

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:

P.SRIKANTH DEPT OF CSE @MIC www.sristudy.in


Page 3

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:

Python Function Argument and Parameter:


There can be two types of data passed in the function.
1) The First type of data is the data passed in the function call. This data is called arguments
2) The second type of data is the data received in the function definition. This data is called
parameters

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:

P.SRIKANTH DEPT OF CSE @MIC www.sristudy.in


Page 4

Parameters:

 Information can be passed to functions as parameter.


 Parameters are specified after the function name, inside the parentheses. You can add as
many parameters as you want, just separate them with a comma.
 The following example has a function with one parameter (fname). When the function is
called, we pass along a first name, which is used inside the function to print the full name:

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:

Formal and Actual Arguments:


When a function is defined, it may have some parameters. These parameters are useful to receive
values from outside of the function. They are called „formal arguments. When we call the
function, we should pass data or values to the function. These values are called actual arguments.
In the following code, a and b are formal arguments and x and y are actual arguments.
Example:
def add(a,b): # a, b are formal arguments
c=a+b
print(c)
x,y=10,15
add(x,y) # x, y are actual arguments
output:

P.SRIKANTH DEPT OF CSE @MIC www.sristudy.in


Page 5

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:

def grocery(item, price):


At the time of calling this function, we have to pass two values and we can mention which value
is for what. For example

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:

Example: Printing passed value


def msg(id,name):
print(id,name)
print(name)
msg(id=101,name='srikanth')
msg(name='MIC',id=12345)

output:

P.SRIKANTH DEPT OF CSE @MIC www.sristudy.in


Page 6

Default Arguments:
We can mention some default value for the function parameters in the definition. Let’s take the
definition of grocery( ) function as:

def grocery(item, price=40.00)


Here, the first argument is item whose default value is not mentioned. But the second argument is
price and its default value is mentioned to be 40.00. at the time of calling this function, if we do
not pass price value, then the default value of 40.00 is taken. If we mention the price value, then
that mentioned value is utilized. So, a default argument is an argument that assumes a default
value if a value is not provided in the function call for that argument.

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:

P.SRIKANTH DEPT OF CSE @MIC www.sristudy.in


Page 7

Variable Length Arguments:


Sometimes, the programmer does not know how many values a function may receive. In that
case, the programmer cannot decide how many arguments to be given in the function definition.
for example, if the programmer is writing a function to add two numbers, he/she can write:
add(a,b)

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:

Python Anonymous / Lambda Function

 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 lambda functions.

It has the following syntax:


lambda arguments: expression

P.SRIKANTH DEPT OF CSE @MIC www.sristudy.in


Page 8

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

Example use with filter()


The filter() function in Python takes in a function and sequence Here is an example use
of filter() function to filter out only even numbers from a list.

my_list = [1, 5, 4, 6, 8, 11, 3, 12]


new_list = list(filter(lambda x: (x%2 == 0) , my_list))
print(new_list)

P.SRIKANTH DEPT OF CSE @MIC www.sristudy.in


Page 9

output:

Example use with map()


The map() function in Python takes in a function and a sequence Here is an example use
of map() function to double all the items in a list.

my_list = [1, 5, 4, 6, 8, 11, 3, 12]


new_list = list(map(lambda x: x * 2 , my_list))
print(new_list)

output:

Fruitful Functions (Function Returning Values)


a function return a value, use the return statement We can return the result or output from the
function using a „return‟ statement in the function body. When a function does not return any
result, we need not write the return statement in the body of the function.

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:

P.SRIKANTH DEPT OF CSE @MIC www.sristudy.in


Page 10

Returning multiple values from a function:

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:

Scope of the Variables in a Function - (Global and Local Variables)

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.

P.SRIKANTH DEPT OF CSE @MIC www.sristudy.in


Page 11

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.

Example: Create a Local Variable


def sri():
y = "mic cse"
print(y)
sri()
output:

Example: Accessing local variable outside the scope:


def sri():
y = "mic cse"
print(y)
sri()
print(y)

output:

Example: Accessing local variable outside the scope:


def myfunction():
a=10
print("Inside function",a) #display 10
myfunction()
print("outside function",a) # Error, not available

output:

P.SRIKANTH DEPT OF CSE @MIC www.sristudy.in


Page 12

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:

The Global Keyword:


In Python, global keyword allows you to modify the variable outside of the current scope. It is
used to create a global variable and make changes to the variable in a local context.
Rules of global Keyword:

 When we create a variable inside a function, it’s local by default.


 When we define a variable outside of 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

P.SRIKANTH DEPT OF CSE @MIC www.sristudy.in


Page 13

Example : Accessing global Variable From Inside a Function


c = 48 # global variable
def sri():
print(c)
sri()
output: 48

Example 2: Modifying Global Variable From Inside the Function


c = 1 # global variable
def add():
c = c + 2 # increment c by 2
print(c)
add()
output:
When we run above program, the output shows an error

UnboundLocalError: local variable 'c' referenced before assignment

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:

P.SRIKANTH DEPT OF CSE @MIC www.sristudy.in


Page 14

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:

P.SRIKANTH DEPT OF CSE @MIC www.sristudy.in


Page 15

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 statement in Python

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.

P.SRIKANTH DEPT OF CSE @MIC www.sristudy.in


Page 16

Example: save this program func28


def fib(n): # write Fibonacci series up to n
a, b = 0, 1
while b < n:
print (b)
a, b = b, a+b
output:

Example: Save this code in the file func31.py


college = {
"name": "MIC",
"estd": 2002,
"place": "kanchikacherla"
}

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:

P.SRIKANTH DEPT OF CSE @MIC www.sristudy.in


Page 17

From .import statement

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:

P.SRIKANTH DEPT OF CSE @MIC www.sristudy.in


Page 18

Example: save this program func29 and run


def myfunc():
print("Hello mic cse")

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.

P.SRIKANTH DEPT OF CSE @MIC www.sristudy.in


Page 19

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)

P.SRIKANTH DEPT OF CSE @MIC www.sristudy.in


Page 20

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.

Installing packages via PIP

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>

P.SRIKANTH DEPT OF CSE @MIC www.sristudy.in


Page 21

One of the six core packages

Using python packages

There are some libraries in python:


Requests: The most famous HTTP Library. It is a must and an essential criterion for every Python
Developer.
Scrapy: If you are involved in web scripting then this is a must have library for you. After using
this library you won’t use any other.

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.

SQLAchemy: It is a database library.

Beautiful Soup: This xml and html parsing library.

Twisted: The most important tool for any network application developer.

NumPy: It provides some advanced math functionalities to python.

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.

P.SRIKANTH DEPT OF CSE @MIC www.sristudy.in


Page 22

Using python packages Example : Basic Pie chart

import matplotlib.pyplot as plt

labels = 'Frogs', 'Hogs', 'Dogs', 'Logs'


sizes = [15, 30, 45, 10]
explode = (0, 0.1, 0, 0) # only "explode" the 2nd slice (i.e. 'Hogs')

fig1, ax1 = plt.subplots()


ax1.pie(sizes, explode=explode, labels=labels, autopct='%1.1f%%',
shadow=True, startangle=90)
ax1.axis('equal') # Equal aspect ratio ensures that pie is drawn as a
circle.

plt.show()

output:

P.SRIKANTH DEPT OF CSE @MIC www.sristudy.in

Potrebbero piacerti anche