Python unit 2
Python unit 2
Python unit 2
UNIT 2
Janhavi Vadke
FUNCTIONS
• A function is a block of organized, reusable
code that is used to perform a single, related
action.
• Functions provide better modularity for the
application and a high degree of code reusing.
• Classification of functions
1) Library functions or Built in functions
2) User defined functions
Defining a Function
• Rules to define a function in Python are
• 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. We 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.
def functionname( parameters ):
"function_docstring"
function_suite
return [expression]
Calling a Function
• Once the basic structure of a function is finalized, we
can execute it by calling it from another function or
directly from the Python prompt
• def printme( str ):
"This prints a passed string into this function"
print (str)
return
• # Now we can call printme function
• printme("This is first call to the user defined function!")
• printme("Again second call to the same function")
math function
• The math module is a standard module in python
and is always available. To use mathematical
functions under this module you have to import
the module using import math and call the
function as math.function_name(parameter)
• math.pow(x, y)
Return x raised to the power y
• math.sqrt(x)
Return the square root of x.
• math.ceil(x)
Return the ceiling of x, the smallest integer greater than or
equal to x. If x is not a float, delegates to x.__ceil__(), which
should return an Integral value.
• math.fabs(x)
Return the absolute value of x.
• math.floor(x)
Return the floor of x, the largest integer less than or equal to x.
If x is not a float, delegates to x.__floor__(), which should
return an Integral value.
• math.fmod(x, y)
Return fmod(x, y), as defined by the platform C library. Note
that the Python expression x % y may not return the same
result
• math.trunc(x)
Rounds up or down towards zero.
Type Conversion Functions
• Sometimes it is necessary to convert values from one type
to another. Python provides a few simple functions that will
allow us to do that.
• int() - constructs an integer number from an integer literal,
a float literal or a string literal
• float() - constructs a float number from an integer literal, a
float literal or a string literal
• str() - constructs a string from a wide variety of data types,
including strings, integer literals and float literals
• long(x) to convert x to a long integer.
• print(float("123.45"))=123.45
• x = int(1) # x will be 1
y = int(2.8) # y will be 2
z = int("3") # z will be 3
Composition
• Composition means that you have two or more
functions where the output of one function is the
input for another.
• Function composition is a way of combining
functions such that the result of each function is
passed as the argument of the next function.
• Function B(FunctionA(x))
• Eg
• >>>Import math
• >>>math.floor(math.sin(45))
Flow of execution
• We have to create a function before we can run it. In other
words, the function definition has to run before the
function gets called.
• Execution always begins at the first statement of the
program. Statements are run one at a time, in order from
top to bottom. Function definitions do not alter the flow of
execution of the program, but remember that statements
inside the function don’t run until the function is called.
• A function call is like a detour in the flow of execution.
Instead of going to the next statement, the flow jumps to
the body of the function, runs the statements there, and
then comes back to pick up where it left off.
• When it gets to the end of the program, it terminates.
Parameters and arguments
• 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.
• def print_twice(bruce):
print(bruce)
print(bruce)
This function assigns the argument to a parameter named bruce.
When the function is called, it prints the value of the parameter
(whatever it is) twice.
>>> print_twice('Spam')
o/p Spam
Spam
1)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.
2)Keyword arguments
• When you use keyword arguments in a function call, the caller identifies
the arguments by the parameter name.
• This allows you 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.
# Function definition is here
def printinfo( name, age ):
"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" )
3)Default Parameter Value
A default argument is an argument that assumes a default
value if a value is not provided in the function call for that
argument
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" )
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.
• 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)
Scope of Variables
• 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
scope of variables
• Local variables -Variables that are defined inside a
function body have a local scope. local variables can be
accessed only inside the function in which they are
declared
• Global variables -variables those defined outside have
a global scope. global variables can be accessed
throughout the program body by all functions.
• whereas When we call a function, the variables
declared inside it are brought into scope
• def print_twice(part1, part2):
cat = part1 + part2
print_twice(cat)
total = 0; # This is global variable.
# Function definition is here
def sum( arg1, arg2 ):
# Add both the parameters and return them."
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
Stack Diagrams
• We must know the variable references that
occurs in code block. To keep track of which
variables can be used where ,it is sometimes
useful to draw a stack diagram.
• Stack diagrams show the value of each variable,
but they also show the function each variable
belongs to.
• Each function is represented by a frame. A frame
is a box with the name of a function beside it and
the parameters and variables of the function
inside it.
• Example:-
• def avrg(n1,n2,n3):
• sum=n1+n2+n3
• avg=sum/3
• print(avg)
• s=11 s->11
t->27
<module>
• t=27 v->8
n1->11
• v=8 n2->27
n3->8
avrg
• avrg(s,t,v) sum->46
avg->15.33
Fruitful functions and Void functions
• The fruitful functions can be referred as the
functions that returns the value. Many of the
math built in functions yield results which are
easy to use.
• Some functions perform an action but don’t
return a value .They are called as void
functions.
Why functions
• • Creating a new function gives you an opportunity to
name a group of statements, which makes your
program easier to read and debug.
• • Functions can make a program smaller by
eliminating repetitive code. Later, if you make a
change, you only have to make it in one place.
• • Dividing a long program into functions allows you to
debug the parts one at a time and then assemble them
into a working whole.
• • Well-designed functions are often useful for many
programs. Once you write and debug one, you can
reuse it.
Importing with from
• Many built in libraries ,modules and packages are provided
by python to support easy programming. These all libraries
we can use in the code by using import statement.
• When the interpreter encounters an import statement ,it
imports the module ,if the module is present in the search
path.
• There are three ways to use import statement in python:-
1) Import statement
• Syntax:-
• import m1[,m2….mN]
• e.g. import math
• print (math.sqrt(4))
2) from….import statement
• It is used to import specific attributes from a
module.
• Syntax:-from mname import nm1[,nm2…..,nmN]
• e.g. from math import pi
• print(pi)
3) from ….import *
• It is used to import all items from a module.
• Syntax:-from mname import *
• e.g from math import *
• print(pi)
• print(sqrt(4))
Incremental development
• As you write larger functions, you might find yourself
spending more time debugging.
• To deal with increasingly complex programs, you might
want to try a process called incremental development.
The goal of incremental development is to avoid long
debugging sessions by adding and testing only a small
amount of code at a time.
• suppose you want to find the distance between two
points, given by the coordinates (x1, y1) and (x2, y2). By
the Pythagorean theorem, the distance is: