0% found this document useful (0 votes)
8 views

Function & Modules IP PDF

Uploaded by

Finn McMissile
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

Function & Modules IP PDF

Uploaded by

Finn McMissile
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 26

PYTHON

FUNCTIONS
&
MODULES
FUNCTIONS & MODULES
 Function and Modules makes a part in the program
structure.
 Defined in the program to break down the
complexity of a given task .
 They perform specific task(sub-task) in a given
task(problem).
 They can be reused in [other] program(s)
FUNCTIONS & MODULES
 Python program contains three components
 Library or Package
 Modules
 Functions / sub-modules
 Library is a collection of various packages.
 Package is a directory of modules.

 Module is a file containing python definitions,


functions, variables, classes and statements with
.py extension.
 A function is a block of organized, reusable code
that is used to perform a single, related action.
FUNCTIONS
 A function is a block of organized, reusable code
that is used to perform a single, related action.
 Functions provide better modularity for an
application and a high degree of code reusing.
 A function is a block of code which only runs when
it is called.
 Data can be passed into a function, known as
parameters.
 A function can return data as a result.
FUNCTIONS
Function Types:
 Python supports three types
 Built-in-functions

 Functions defined in a module


 User defined functions
FUNCTIONS
 Defining a Function
To define functions to provide the required functionality the following simple rules to be
followed:
 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 first statement of a function can be an optional statement - the documentation
string of the function or docstring.
 The code block within every function starts with a colon (:) and is indented.

 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.
FUNCTIONS
SYNTAX:
def functionname( parameters ):
"function_docstring"
function_suite
return [expression]
By default, parameters have a positional behavior and you need to inform them in the same
order that they were defined.

Example
The following function takes a string as input parameter and prints it on standard screen.
def printme( str ):
"This prints a passed string into this function"
print str
return
FUNCTIONS
Calling a Function:
 Defining a function only gives it a name, specifies the parameters that are to be included in the
function and structures the blocks of code.
 Once the basic structure of a function is finalized, it can be executed by calling it from another
function or directly from the Python prompt.
Following is the example to call printme() function −
#!/usr/bin/python

# Function definition is here


def printme( str ):
"This prints a passed string into this function"
print str
return;

# Now you can call printme function


printme("I'm first call to user defined function!")
printme("Again second call to the same function")

Output:
I'm first call to user defined function!
Again second call to the same function
FUNCTIONS
Arguments
 Information can be passed into functions as arguments.
 Arguments are specified after the function name, inside the parentheses.
 We can add as many arguments as we want, just separate them with a comma.
 The following example has a function with one argument (fname). When the
function is called, we pass along a first name, which is used inside the function
to print the full name:

def my_function(fname):
print(fname + " Refsnes")

my_function("Emil")
my_function("Tobias")
my_function("Linus")

Output:
Emil Refsnes
Tobias Refsnes
Linus Refsnes
FUNCTIONS
Arguments / Parameters
 What is parameter? Is it same as argument?
 Yes.
 The terms parameter and argument can be used for the same thing:
 information that are passed into a function.
From a function's perspective:
 A parameter is the variable listed inside the parentheses in the
function definition.
 An argument is the value that are sent to the function when it is
called.
Number of Arguments
 By default, a function must be called with the correct number of
arguments.
 Meaning that if a function expects 2 arguments, then we have to
call the function with 2 arguments, not more, and not less.
FUNCTION ARGUMENTS
A function can be called by using the following types
of formal arguments −
 Required arguments

 Keyword arguments

 Default arguments

 Variable-length arguments
FUNCTION 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(), we definitely need to pass one argument, otherwise it
gives a syntax error as follows −
 # Function definition is here
def printme( str ):
"This prints a passed string into this function"
print str
return;
# Now you can call printme function

printme()

When the above code is executed, it produces the following error −


Traceback (most recent call last): File "test.py", line 11, in <module> printme();
TypeError: printme() takes exactly 1 argument (0 given)
- Meaning the function requires 1 argument, but it is called with no / 0 argument
FUNCTION ARGUMENTS
Keyword arguments
 Keyword arguments are related to the function calls.
 When we use keyword arguments in a function call, the caller identifies
the arguments by the parameter name.
 This allows us 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.
The keyword calls to the printme() function can be in the following ways −
# Function definition is here
def printme( str ):
"This prints a passed string into this function"
print str
return;

# Now you can call printme function


printme( str = "My sting")
FUNCTION ARGUMENTS
Keyword arguments
 The following example gives more clear picture. Note that the order of
parameters does not matter.
# Function definition is here
def printinfo( name, age ):
"This prints a passed info into this function"
print ("Name: ", name, "Age ", age)
return;

# Now you can call printinfo function


printinfo( age=50, name="miki" )

When the above code is executed, it produces the following result −

Name: miki Age 50


FUNCTION ARGUMENTS
Default arguments
 Default Parameter Value

 The following example shows how to use a default


parameter value.
 If we call the function without argument, it uses
the default value:
def = "Norway"):
my_function(country
print("I am from " + country)

my_function("Sweden")
my_function("India")
my_function()
my_function("Brazil")
FUNCTION ARGUMENTS
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 −

#!/usr/bin/python
# Function definition is here
def printinfo( name, age = 35 ):
"This prints a passed info into this function"
print "Name: ", name
print "Age ", age
return;
# Now you can call printinfo function
printinfo( age=50, name="miki" )
printinfo( name="miki" )
FUNCTION ARGUMENTS
Default arguments
# Now you can call printinfo function
printinfo( age=50, name="miki" )
printinfo( name="miki" )

When the above code is executed, it produces the following result −

Name: miki
Age 50
Name: miki
Age 35
FUNCTION ARGUMENTS
Variable-length arguments
 You may need to process a function for more arguments than you specified while
defining the function.
 These arguments are called variable-length arguments and are not named in
the function definition, unlike required and default arguments.
 Syntax for a function with non-keyword variable arguments is this −

def functionname([formal_args,] *var_args_tuple ):


"function_docstring"
function_suite
return [expression]
FUNCTION ARGUMENTS
Variable-length arguments
 An asterisk (*) is placed before the variable name that holds the values of all nonkeyword variable arguments.
 This tuple remains empty if no additional arguments are specified during the function call. Following is a simple
example −

#!/usr/bin/python
# Function definition is here

def printinfo( arg1, *vartuple ):


"This prints a variable passed arguments"
print ("Output is: " )
print arg1
for var in vartuple:
print var
return;

# Now you can call printinfo function


printinfo( 10 )
printinfo( 70, 60, 50 )

Output is:
10
Output is:
70
60
50
FUNCTION ARGUMENTS
The return Statement
 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.
 All the above examples are not returning any value. You can return a value from a
function as follows −

# Function definition is here

def sum( arg1, arg2 ):


# Add both the parameters and return them."
total = arg1 + arg2
print (“Inside the function : ", total )
return total;
# Now you can call sum function
total = sum( 10, 20 );
print "Outside the function : ", total

When the above code is executed, it produces the following result −


Inside the function : 30
Outside the function : 30
FUNCTION - EXERCISE
1. WAP to do basic arithmetic operation after
selecting the menu for the operation to do
and reading the two integer numbers call
the respective function to complete the
process. The function returns the result
and then displayed.
2. WAP to generate the following series after
reading the required data from the user.
Define function genterm()to return the
generated term. Store the terms in a list
and then display the series.
i. a a2 a3 a4 a5 … an
ii. 1! 2! 3! … n!
MODULE
 A module is a file consisting of python
code that can define functions, classes and
variables related to a particular task.
 A module allows to organize the code by
grouping related code, which makes code
easier to understand and use
 It is python file with extension py,
example arithoperation.py is a module with
name arithoperation
 _name_ is the variable that holds the
module name
MODULE CONTINUED…
 A module can be used by any program by
importing the file into the current file(main
file)
Syntax:
import <modulename>
import module1 [,module2 [,…moduleN]]

 Instead of entire module Specific methods can


be imported
Syntax: from <module_name> import <function_name(s)>

 A function or method from a module can be called /


invoked / accessed by giving the function/method
name along with the module name in which it is
defined separated by dot(.).

Syntax: <module_name>.<function_name>
MODULE CONTINUED…

Example: module to calculate area is developed as shown


below,

#To develop area module - "area.py"

import math

def circle_area(radius):
#pi * r * r
return math.pi * radius * radius

def square_area(side):
return side * side

def rectangle_area(length, breadth):


# length * breadth
return length * breadth
MODULE CONTINUED…
Example: Module to calculate area is developed as shown below, and
program math1 is developed to show how area module is imported and used,

Source Code: Source Code:


#To develop area module -
"area.py" #importing the module area in
math1.py module
import math
import area
def circle_area(radius):
#pi * r * r print( area.circle_area(5))
return math.pi * radius * radius print( area.square_area(5))
print( area.rectangle_area(5,7))
def square_area(side):
return side * side
Output:
def rectangle_area(length, 78.53981633974483
breadth): 25
# length * breadth 35
return length * breadth
MODULE CONTINUED…
Retrieving object from the module:
-Function dir() is used
# in mode,
>>> import area
>>> dir (area)
['__builtins__', '__cached__', '__doc__', '__file__',
'__loader__', '__name__', '__package__', '__spec__',
'circle_area', 'math', 'rectangle_area', 'square_area']
>>>
Various form of using import statement:
# importing specific function alone Output:
from area import circle_area
314.1592653589793
print(circle_area(10))
Output:
# importing for accessing all function from the module
from area import * 314.1592653589793
16
print(circle_area(10)) 50
print(square_area(4)) >>>
print(rectangle_area(5,10))

You might also like