PPS Unit 3

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 44

Programming and Problem

Solving

Department of Computer Engineering,


Pimpri Chichwad College of Engineering &
Research,
Ravet
Unit 3
Functions and Modules
Syllabus
⚫ Need for functions,
⚫ Function: definition, call,
⚫ variable scope and lifetime,
⚫ the return statement.
⚫ Defining functions,
⚫ Lambda or anonymous function,
⚫ documentation string,
⚫ good programming practices.
⚫ Introduction to modules,
⚫ Introduction to packages in Python,
⚫ Introduction to standard library modules.
⚫ A function is a block of statements that performs a specific
task.
OR
⚫ A function can be defined as the organized block of reusable
code, which can be called whenever required.
⚫ to perform a same task in that program more than once, you
have two options:
a) Use the same set of statements every time you want to
perform the task

b) Create a function to perform that task, and just call it every


time you need to perform that task.

⚫ Using option (b) is a good practice and a good programmer


always uses functions while writing code in any language.
Need for functions
⚫ Functions are used

a) To improve the readability of code.

b) Improves the reusability of the code, same


function can be used in any program rather than
writing the same code from scratch.

c) Debugging of the code would be easier if


you use functions, as errors are easy to be traced.

d) Reduces the size of the code, duplicate set of


statements are replaced by function calls.

The function is also known as procedure or subroutine in other


programming languages
P y th o n F u n c tio n

⚫ The function contains the set of programming


statements enclosed by {}.
⚫ A function can be called multiple times
⚫ It helps to programmer to break the program into the
smaller part.
⚫ It organizes the code very effectively and avoids the
repetition of the code.
⚫ As the program grows, function makes the program
more organized.
⚫ Python provide us various inbuilt functions
like range() or print(). Although, the user can create its
functions, which can be called user-defined functions.
There are mainly two types of
functions.

⚫User-define functions - The user-defined


functions are those define by the user to
perform the specific task.
⚫Built-in functions - The built-in functions
are those functions that are pre-defined in
Python.
Defining functions

⚫ 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.

⚫ The statement return [expression] exits a function,


optionally passing back an expression to the caller.

⚫ A return statement with no arguments is the same as


return None.
Syntax:

def my_function(parameters):
function_block
return expression
⚫ The def keyword, along with the function name is
used to define the function.

⚫ The identifier rule must follow the function


name.

⚫ A function accepts the parameter (argument), and


they can be optional.

⚫ The function block is started with the colon (:), and


block statements must be at the same indentation.

⚫ The return statement is used to return the value. A


function can have only one return
Function call
⚫ In Python, after the function is created, we can call it from
another function.
⚫ A function must be defined before the function call;
otherwise, the Python interpreter gives an error.
⚫ To call the function, use the function name followed
by the parentheses.

#function definition
def hello_world():
print("hello world")

# function calling
hello_world()
return statement
⚫ The return statement is used at the end of the
function and returns the result of the function.
⚫ It terminates the function execution and transfers the
result where the function is called.
⚫ The return statement cannot be used outside of the
function.

return [expression_list]

⚫ It can contain the expression which gets evaluated


and value is returned to the caller function.
⚫ If the return statement has no expression or does not
exist itself in the function then it returns
the None object.
Example 1
# Defining function
def sum():
a = 10
Output:
b = 20 The sum is: 30
c = a+b
return c
# calling sum() function in print state
ment
print("The sum is:",sum())

In the above code, we have defined the function named sum, and it has
a statement c = a+b, which computes the given values, and the result is
returned by the return statement to the caller function.
Example 2 Creating function without
return statement

# Defining function
def sum():
a = 10
b = 20
c = a+b

# calling sum() function in print statement

print(sum()) Output: None


Function Arguments

call a function by using the following types of formal


arguments −

● Required arguments
● Keyword arguments

● Default arguments
● Variable-length arguments
Required arguments

Required arguments 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.
To call the function printme(), definitely need to
pass one argument, otherwise it gives a syntax
error as follows −
# Function definition is here
def printme( str ):
print str
return;

# Now you can call printme function


printme()
Keyword arguments

Keyword arguments are related to the function calls.

For keyword arguments in a function call, the caller


identifies the arguments by the parameter name.

This allows to skip arguments or place them out of order


because the Python interpreter is able to use the keywords
provided to match the values with parameters.
def printme( str ):
print str
return;
My string
# Now you can call printme function
printme( str = "My string")
Default arguments

A default argument is an argument that assumes a


default value if a value is not provided in the
function call for that argument.
The following example gives an idea on default
arguments, it prints default age if it is not passed
# Function definition is here
def printinfo( name, age = 35 ):
print "Name: ", name
print "Age ", age
return;

# Now you can call printinfo function


printinfo( age=50, name="miki" )
printinfo( name="miki" )
Variable-length arguments
Example of Variable length
arguments

def add(a,b,*arg):
m=a+b
for value in arg:
m=m+value
return m

d=add(1,2,3,4,5,6) #call with six arguments


e=add(1,2,3) # call with three arguments
print(d)
print(e)

OUTPUT : ????
Variable scope and lifetime,
All variables in a program may not be accessible at all
locations in that program. This depends on where you have
declared a variable.

The scope of a variable determines the portion of the


program where you can access a particular identifier.

There are two basic scopes of variables in Python −

● Global variables
● Local variables
Example

total = 0; # This is global variable.

def sum( arg1, arg2 ):


total = arg1 + arg2; # Here total is local variable.
print "Inside the function local total : ", total
return total;

# Now you can call sum function


sum( 10, 20 );
print "Outside the function global total : ", total

Inside the function local total : 30


Outside the function global total : 0
Lambda or anonymous function
⚫ Python Lambda function is known as the
anonymous function that is defined without a
name.
⚫ The anonymous functions are declared by
using the lambda keyword.
⚫ However, Lambda functions can accept any
number of arguments, but they can return
Syntax
only one value in the form of expression.
lambda arguments: expression
Example 1

# a is an argument and a+10 is an expression which got evaluated and


returned.

x = lambda a:a+10

# Here we are printing the function object

print(x)

print("sum = ",x(20))

Output:
<function <lambda> at
0x0000019E285D16A8>
sum = 30
'''this is lambda function'''

area = lambda r:3.14*r*r


print(area(8))
print(area(3))
Example 2

x = lambda a, b, c : a + b + c
print(x(5, 6, 2))

output
13
Why Use Lambda Functions?
The power of lambda is better shown when you use them as an
anonymous function inside another function.
Introduction to modules

⚫ Consider a module to be the same as a code library.


⚫ A file containing a set of functions you want to
include in your application.
⚫ To create a module just save the code you want in a
file with the file extension .py:
Create a Module

Save this code in a file named mymodule.py

#module to compute area of triagle and circle

def area_triagle(x,y):
area=(1/2)*x*y
print("Area of triangle :",area)

def area_circle(r):
print("Area of circle :",3.14*r*r)

x=100
Use a Module

Use the module by using the import statement:


⚫ When using a function from a module, use the
syntax: module_name.function_name.
area_ex.py

import mymodule

mymodule.area_triagle(10,20)

mymodule.area_circle(6)

print(" answer :",mymodule.x*100)


Introduction to packages in Python
We usually organize our files in different folders and subfolders based on some criteria, so that they
can be managed easily and efficiently.
For example, we keep all our games in a Games folder and we can even subcategorize according to
the genre of the game or something like this. The same analogy is followed by the Python package.
A Python module may contain several classes, functions, variables..
whereas a Python package can contains several module. In simpler terms a package is folder that
contains various modules as files.
Creating Package
Let’s create a package named mypckg that will contain two modules mod1 and mod2. To
create this module follow the below steps –

● Create a folder named mypckg.


● Inside this folder create an empty Python file i.e. __init__.py
● Then create two modules mod1 and mod2 in this folder.

Mod1.py

def gfg():
print("Welcome to
GFG")

Mod2.py

def sum(a, b):


return a+b
● __init__.py helps the
The hierarchy of the our Python interpreter to
package looks like this – recognise the folder as
package.
mypckg ● It also specifies the
| resources to be imported
| from the modules.
---__init__.py ● If the __init__.py is
| empty this means that all
| the functions of the
---mod1.py modules will be imported.
| ● We can also specify the
functions from each
|
module to be made
---mod2.py available.
Import Modules from a Package

Syntax:
import package_name.module_name

Import Specific function from the module


from mypckg.mod1 import gfg
from mypckg.mod2 import sum
from math import *
print(pi)
print(factorial(6))

Output:
3.141592653589793
720

You might also like