[go: up one dir, main page]

0% found this document useful (0 votes)
10 views82 pages

Unit4-Functions and Classes

Python btech

Uploaded by

reeve0317
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)
10 views82 pages

Unit4-Functions and Classes

Python btech

Uploaded by

reeve0317
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/ 82

UNIT4- FUNCTIONS and

CLASSES
n Advantage of modularizing program into functions,
function definition and function invocation.
n Function arguments: default, keyword and positional
arguments.
n Scope and lifetime of a variable. Recurrence relations
and Recursion
n Advantage of using classes, defining class data
members & functions and accessing using objects.
n Constructors and destructors in a class,
parameterized constructors
Introducing Functions
Mathematical concept of a function

A function is a relationship or mapping between one


or more inputs and a set of outputs.

Here, f is a function that operates on the inputs x and y.


The output of the function is z
n Programming functions are much more
generalized and versatile

n Appropriate function definition and use is so


critical to proper software development that
virtually all modern programming languages
support both built-in and user-defined
functions.
A function is like a subprogram, a small program
inside of a program.

Definition
n Function is a self-contained block of
code that encapsulates a specific task
or related group of tasks.
Built in functions:-
len() returns length of the argument passed to it
n Each of the built-in functions performs a specific task.

n The code that accomplishes the task is defined


somewhere, but you don’t need to know where or
even how the code works.

n All you need to know about is the


function’s interface:
n What arguments (if any) it takes

n What values (if any) it returns


Different Nomenclature, same
purpose
n Subroutines
n Procedures
n Methods
n Subprograms
n Functions
Simple Examples: flipping a channel on TV,
adjusting volume
Why functions?
n Program to convert temp in Celsius to Fahrenheit (multiple
times)
n Fahrenheit=(9/5)celsius+32

The idea is to put some


commonly or repeatedly done
tasks together and make a
function, so that instead of
writing the same code again and
again for different inputs, we
can call the function.

Inconsistencies and ambiguities


Benefits
Abstraction and Reusability
n The abstraction of functionality into a
function definition is an example of the Don’t
Repeat Yourself (DRY) Principle of software
development.
n Changes in code required only at one place
Benefits
Modularity
n Functions allow complex
processes to be broken
up into smaller steps.
Note: The def keyword introduces a new Python function definition.
Modularity
n Breaking a large task into smaller, bite-
sized sub-tasks helps make the large
task easier to think about and manage.

n As programs become more complicated,


it becomes increasingly beneficial to
modularize them in this way.
Namespace separation
n A namespace is a region of a program in
which identifiers have meaning.

n when a Python function is called, a new namespace


is created for that function, one that is distinct from
all other namespaces that already exist.

n you can use variable names and identifiers without


worrying about whether they’re already used
elsewhere outside the function
Defining a Python Function

The final item, <statement(s)>, is called the body of the function


Calling a Function

<arguments>are the values passed into the function. They correspond


to the <parameters> in the Python function definition.

You can define a function that doesn’t take any arguments, but
the parentheses are still required. Both a function definition and
a function call must always include parentheses, even if they’re
empty.
Getting Started
Stub
n Sometimes you may want to define an empty function that
does nothing. This is referred to as a stub, which is usually a
temporary placeholder for a Python function that will be fully
implemented at a later time.

n Just as a block in a control structure can’t be empty, neither can


the body of a function. To define a stub function, use the pass
statement:
When the function is called, the

Argument Passing
arguments that are passed
(6, 'bananas', and 1.74) are bound to
the parameters in order, as though
by variable assignment:

n Positional Arguments
n Also called “required arguments”
the order of the arguments in the call must match the order of
the parameters in the definition. There’s nothing to stop you
from specifying positional arguments out of order, of course:
>>>f('bananas', 1.74, 6)
bananas 1.74 cost $6.00

The function may even still run, as it did in the example above,
but it’s very unlikely to produce the correct results.
n With positional arguments, the arguments in the call and the
parameters in the definition must agree not only in order but
in number as well.

n That’s the reason positional arguments are also referred to as required


arguments.
Keyword Arguments
n When you’re calling a function, you can specify arguments in
the form <keyword>=<value>.

n In that case, each <keyword> must match a parameter in the


Python function definition.

n For example, the previously defined function f() may be called


with keyword arguments as follows:
n Referencing a keyword that doesn’t
match any of the declared parameters
generates an exception:
n Using keyword arguments lifts the
restriction on argument order.
n Like with positional arguments, though,
the number of arguments and
parameters must still match:

So, keyword arguments allow flexibility in the order


that function arguments are specified, but the
number of arguments is still rigid.
When positional and keyword arguments are both
present, all the positional arguments must come first:

Once you’ve specified a keyword argument, there can’t be any positional


arguments to the right of it.
Default Parameters
n If a parameter specified in a Python function
definition has the form <name>=<value>,
then <value> becomes a default value for that
parameter.
n Parameters defined this way are referred to
as default or optional parameters.
Observe ….
Summary:
n Positional arguments must agree in order and
number with the parameters declared in the function
definition.
n Keyword arguments must agree with declared
parameters in number, but they may be specified in
arbitrary order.
n Default parameters allow some arguments to be
omitted when the function is called
Example on Functions
Definition and calls
n Happy Birthday lyrics…
def main():
print("Happy birthday to you!" )
print("Happy birthday to you!" )
print("Happy birthday, dear Fred...")
print("Happy birthday to you!")

n Gives us this…
>>> main()
Happy birthday to you!
Happy birthday to you!
Happy birthday, dear Fred...
Happy birthday to you!
n There’s some duplicated code in the
program! (print("Happy birthday to you!"))
n We can define a function to print out
this line:
def happy():
print("Happy birthday to you!")

n With this function, we can rewrite our


program.
n The new program –
def singFred():
happy()
happy()
print("Happy birthday, dear Fred...")
happy()

n Gives us this output –


>>> singFred()
Happy birthday to you!
Happy birthday to you!
Happy birthday, dear Fred...
Happy birthday to you!
n Creating this function saved us a lot of
typing!
n What if it’s Lucy’s birthday? We could
write a new singLucy function!
def singLucy():
happy()
happy()
print("Happy birthday, dear Lucy...")
happy()
n We could write a main program to sing
to both Lucy and Fred
def main():
singFred()
print()
singLucy()

n This gives us this new output


>>> main()
Happy birthday to you!
Happy birthday to you!
Happy birthday, dear Fred..
Happy birthday to you!

Happy birthday to you!


Happy birthday to you!
Happy birthday, dear Lucy...
Happy birthday to you!
n This is working great! But… there’s still
a lot of code duplication.
n The only difference between singFred
and singLucy is the name in the third
print statement.
n These two routines could be collapsed
together by using a parameter.
Functions, Informally
n The generic function sing
def sing(person):
happy()
happy()
print("Happy birthday, dear", person + ".“)
happy()

n This function uses a parameter named


person. A paramater is a variable that is
initialized when the function is called.
n Our new output –
>>> sing("Fred")
Happy birthday to you!
Happy birthday to you!
Happy birthday, dear Fred.
Happy birthday to you!

n We can put together a new main


program!
n Our new main program:
def main():
sing("Fred")
print()
sing("Lucy")

n Gives us this output:


>>> main()
Happy birthday to you!
Happy birthday to you!
Happy birthday, dear Fred.
Happy birthday to you!

Happy birthday to you!


Happy birthday to you!
Happy birthday, dear Lucy.
Happy birthday to you!
Functions and Parameters:
The Details
n The scope of a variable refers to the
places in a program a given variable
can be referenced.
Functions and Parameters:
The Details
n Each function is its own little subprogram.
The variables used inside of a function are
local to that function, even if they happen to
have the same name as variables that appear
inside of another function.
n The only way for a function to see a variable
from another function is for that variable to
be passed as a parameter.
Functions and Parameters:
The Details

n Execution continues in this way with two


more trips to happy.
n When Python gets to the end of sing,
control returns to main and continues
immediately following the function call.
Functions and Parameters:
The Details

n Notice that the person variable in sing has


disappeared!
n The memory occupied by local function
variables is reclaimed when the function
exits.
n Local variables do not retain any values from
one function execution to the next.
Functions and Parameters:
The Details
n The next statement is the bare print,
which produces a blank line.
n Python encounters another call to
sing, and control transfers to the
sing function, with the formal
parameter “Lucy”.
Functions and Parameters:
The Details

n The body of sing is executed for Lucy


with its three side trips to happy and
control returns to main.
Functions and Parameters:
The Details
Functions and Parameters:
The Details
n One thing not addressed in this
example was multiple parameters.

n In this case the formal and actual


parameters are matched up based on
position, e.g. the first actual parameter
is assigned to the first formal
parameter, the second actual parameter
is assigned to the second formal
parameter, etc.
Getting Results from a
Function
n Passing parameters provides a
mechanism for initializing the variables
in a function.
n Parameters act as inputs to a function.
n We can call a function many times and
get different results by changing its
parameters.
Functions That Return Values
n Example of functions that return values
to the caller.
discRt = math.sqrt(b*b – 4*a*c)
n The value b*b – 4*a*c is the actual
parameter of math.sqrt.
n We say sqrt returns the square root of
its argument.
Functions That Return Values
n This function returns the square of a number:
def square(x):
return x*x
n When Python encounters return, it exits the
function and returns control to the point
where the function was called.
n In addition, the value(s) provided in the
return statement are sent back to the
caller as an expression result.
Functions That Return Values
n >>> square(3)
9
n >>> print(square(4))
16
n >>> x = 5
>>> y = square(x)
>>> print(y)
25
n >>> print(square(x) + square(3))
34
Functions That Return Values
n We can use the square function to write
a routine to calculate the distance
between (x1,y1) and (x2,y2).

n def distance(p1, p2):


dist = math.sqrt(square(p2.getX() - p1.getX()) +
square(p2.getY() - p1.getY()))
return dist
Functions That Return Values
n Sometimes a function needs to return
more than one value.
n To do this, simply list more than one
expression in the return statement.

n def sumDiff(x, y):


sum = x + y
diff = x – y
return sum, diff
Functions That Return Values
n When calling this function, use
simultaneous assignment.
n num1, num2 = eval(input("Enter two numbers (num1, num2) "))
s, d = sumDiff(num1, num2)
print("The sum is", s, "and the difference is", d)

n As before, the values are assigned


based on position, so s gets the first
value returned (the sum), and d gets
the second (the difference).
Functions That Return Values
n One “gotcha” – all Python functions
return a value, whether they contain a
return statement or not. Functions
without a return hand back a special
object, denoted None.
n A common problem is writing a value-
returning function and omitting the
return!
Functions That Return Values
n If your value-returning functions
produce strange messages, check to
make sure you remembered to include
the return!
Functions that Modify
Parameters
n Suppose you are writing a program that
manages bank accounts. One function
we would need to do is to accumulate
interest on the account. Let’s look at a
first-cut at the function.
n def addInterest(balance, rate):
newBalance = balance * (1 + rate)
balance = newBalance
Functions that Modify
Parameters
n The intent is to set the balance of the
account to a new value that includes
the interest amount.
n Let’s write a main program to test this:
def test():
amount = 1000
rate = 0.05
addInterest(amount, rate)
print(amount)
Functions that Modify
Parameters
n We hope that that the 5% will be added
to the amount, returning 1050.
n >>> test()
1000
n What went wrong? Nothing!
Functions that Modify
Parameters
The first two lines of
def addInterest(balance, rate):
n newBalance = balance * (1 + rate)

the test function


balance = newBalance

create two local


def test():
amount = 1000

variables called
rate = 0.05
addInterest(amount, rate)

amount and rate print(amount)

which are given the


initial values of
1000 and 0.05,
respectively.
Functions that Modify
Parameters
n Control then transfers def addInterest(balance, rate):
newBalance = balance * (1 + rate)
to the addInterest balance = newBalance

function. def test():

n The formal parameters amount = 1000


rate = 0.05
balance and rate are addInterest(amount, rate)
assigned the values of print(amount)

the actual parameters


amount and rate.
n Even though rate
appears in both, they
are separate variables
(because of scope
rules).
Functions that Modify
Parameters
The assignment of
def addInterest(balance, rate):
n newBalance = balance*(1 + rate)

the parameters balance = newBalance

causes the variables def test():

balance and rate amount = 1000


rate = 0.05
in addInterest to addInterest(amount, rate)
print(amount)
refer to the values
of the actual
parameters!
Functions that Modify
Parameters
Functions that Modify
Parameters
Executing the first
def addInterest(balance, rate):
n newBalance = balance * (1 +

line of rate)
balance = newBalance
addInterest
def test():
creates a new amount = 1000

variable, rate = 0.05


addInterest(amount, rate)
newBalance. print(amount)

n balance is then
assigned the value
of newBalance.
Functions that Modify
Parameters
n balance now refers def addInterest(balance, rate):
newBalance = balance * (1 + rate)
to the same value as balance = newBalance

newBalance, but def test():

this had no effect on amount = 1000


rate = 0.05
amount in the test addInterest(amount, rate)
print (amount)
function.
Functions that Modify
Parameters
Functions that Modify
Parameters
n Execution of def addInterest(balance, rate):

addInterest has newBalance = balance * (1 +


rate)
completed and control balance = newBalance

returns to test.
def test():
n The local variables, amount = 1000
including the rate = 0.05

parameters, in addInterest(amount, rate)


print(amount)
addInterest go
away, but amount and
rate in the test
function still refer to
their initial values!
Functions that Modify
Parameters
n To summarize: the formal parameters
of a function only receive the values of
the actual parameters. The function
does not have access to the variable
that holds the actual parameter.
n Python is said to pass all parameters by
value.
To resolve the issue, declare another
variable amount to get the value
returned from the function
def addInterest(balance, rate):
newBalance = balance * (1 + rate)
return newBalance

def test():
amount = 1000
rate = 0.05
amount = addInterest(amount, rate)
print(amount)

test()
Functions that Modify
Parameters
n Instead of looking at a single account, say we
are writing a program for a bank that deals
with many accounts. We could store the
account balances in a list, then add the
accrued interest to each of the balances in
the list.
n We could update the first balance in the list
with code like:
balances[0] = balances[0] * (1 + rate)
Functions that Modify
Parameters
n This code says, “multiply the value in
the 0th position of the list by (1 + rate)
and store the result back into the 0th
position of the list.”
n A more general way to do this would be
with a loop that goes through positions
0, 1, …, length – 1.
Functions that Modify
Parameters
# addinterest3.py
# Illustrates modification of a mutable parameter (a list).

def addInterest(balances, rate):


for i in range(len(balances)):
balances[i] = balances[i] * (1+rate)

def test():
amounts = [1000, 2200, 800, 360]
rate = 0.05
addInterest(amounts, 0.05)
print(amounts)

test()
Functions that Modify
Parameters
n Remember, our original code had these
values:
[1000, 2200, 800, 360]

n The program returns:


[1050.0, 2310.0, 840.0, 378.0]

n What happened? Python passes


parameters by value, but it looks like
amounts has been changed!
Functions that Modify
Parameters
The first two lines of
def addInterest(balances, rate):
n for i in range(len(balances)):

test create the


balances[i] = balances[i] *
(1+rate)

variables amounts def test():

and rate.
amounts = [1000, 2200, 800, 360]
rate = 0.05
addInterest(amounts, 0.05)
n The value of the print(amounts)

variable amounts is
a list object that
contains four int
values.
Functions that Modify
Parameters
Functions that Modify
Parameters
n Next, addInterest def addInterest(balances, rate):
for i in range(len(balances)):

executes. The loop


balances[i] = balances[i] *
(1+rate)

goes through each def test():

index in the range 0,


amounts = [1000, 2200, 800, 360]
rate = 0.05

1, …, length –1 and
addInterest(amounts, 0.05)
print(amounts)

updates that value


in balances.
Functions that Modify
Parameters
Functions that Modify
Parameters
n In the diagram the old def addInterest(balances, rate):
for i in range(len(balances)):
values are left hanging balances[i] = balances[i]
around to emphasize * (1+rate)

that the numbers in the def test():


boxes have not amounts = [1000, 2200, 800,
changed, but the new 360]

values were created rate = 0.05


addInterest(amounts, 0.05)
and assigned into the print amounts
list.
n The old values will be
destroyed during
garbage collection.
Functions that Modify
Parameters
n When addInterest terminates, the
list stored in amounts now contains the
new values.
n The variable amounts wasn’t changed
(it’s still a list), but the state of that list
has changed, and this change is visible
to the calling program.
Functions that Modify
Parameters
n Parameters are always passed by value.
However, if the value of the variable is
a mutable object (like a list of graphics
object), then changes to the state of
the object will be visible to the calling
program.
Summary
n So far, functions have been used as a
mechanism for reducing code duplication.
n Another reason to use functions is to make
your programs more modular.
n As the algorithms you design get increasingly
complex, it gets more and more difficult to
make sense out of the programs.
Examples- Passing Dictionary
def func(d):
for key in d:
print("key:", key, "Value:", d[key])

D = {'a':1, 'b':2, 'c':3}


func(D)
Examples: Passing Tuple
n Case 1: fnc(a, b) – Sends a and b as
separate elements to fnc.
n Case 2: fnc((a, b)) – Sends (a, b), whole
tuple as 1 single entity, one element.
n Case 3: fnc(*(a, b)) – Sends both, a and
b as in Case 1, as separate integers.

You might also like