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

Function 12

Uploaded by

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

Function 12

Uploaded by

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

Working with

Functions
Introduction
Function
It is a subprogram that acts on data and often return
value(s).
Understanding function
Let us consider polynomial function f(x)=2x2
for x =1 it gives 2
for x=3 it gives 18
Where x is argument and f() is function
Advantages of using function
1. To make program handling easier i.e. only a small part of
program dealt with at a time.
2. To reduce the program size.
3. Make program more readable and understandable.
4. A function once defined can be called/invoked as many
time as needed by using its names without having to
rewrite code.
5. Reusable functions can be put in a library modules. These
module can be imported and used when needed in other
programs.
Python Function Types

1. Built-in Function :- These are pre-defined functions and


are always available for use. Ex. len(), type(),int() etc.
2. Function defied in modules:- These functions are pre-
defined in particular modules and can only be used
when the corresponding modules is imported.
Example- cos() then we have to import math modules.
3. User defined function:- These are defined by the
programmer
Defining function in Python
• General format of function definition
def <function_name> ([parameter]) :
<statement>
<statement>
.
.
.
return
• Where def means function definition is starting
• <function_name> : It is the function name any valid identifier
name.
• parameter : variables that are listed within the parentheses of a
function.
• There is colon at the end of def line, meaning it need a block of
statement.
• The statements indented below the function define the working
of the function. This is called body of the function. The function
body may or may not return any value. If a function return any
value(s) it must contain return statement. A not returning any
value can still have a return statement without any expression or
value. Only one return allowed in a function.
example
def sum(x,y) :
s=x+y
return s
Or
def sum(x,y) :
s=x+y
print(s)
Or
def greet() :
print(“Hello”)
Note:- The function definition does not execute the function body, this
execute only when the function is called or invoked.
Structure of a Python program
• The python interpreter starts the execution of the program from the top level
statement. Python gives a special name to top level statement as _main_
• Python store the name in a built in variable _name_
(we need not declare this)
• Example
def greet() :
print(“Hello”)
print(“At the top most level right now”)#top level statement
print(“inside”,_name_) # top level statement
• Output
At the top most level right now
inside _main_
Calling / invoking a function

• To use the function defined earlier we need to call that


function. The syntax to call the function
• <function_name>(value to pass as parameter)
Eg. def sum(x,y) :
s=x+y
return s
To call above function
sum(5,6)
Arguments and Parameter
• Arguments : The values being passed through a function-call
statement are called arguments/actual argument. Argument can be
literals, variables or expression.
• Parameter : The values received in the function definition are called
parameter/formal parameter or formal arguments.
Note:- if we passing values of immutable types( number, strings etc) to
the called function then the called function can’t alter the values
passed arguments but if passing the values of mutable types(list,
dictionaries) then called function able to change them.
- Immutable types implemented by call by value and mutable type
implemented by call by reference.
Passing Parameters
Python support three types of parameter

Default arguments ar
l gu Ke
a
n ts m yw
o ar en or
s iti en d gu ts d
Po gum uire rs) m (na
en m
ar eq ete ts) ed
(R am
a r
P
Positional / Required arguments
When the function call statements must match the number and order of
arguments as defined in the function definition, this is called the positional
argument matching.
Example :
def sum(a,b,c) :
d= a+b+c
return d
Then the positional function call for the above function
sum(x,y,z) or sum(5,x,y) or sum(2,3,6)
Thus through such function calls,
* The arguments must be provided for all parameter (required)
* The values of arguments are matched with parameters, positional (order) wise
(positional)
Default Arguments
• A function having default value in the function call statements. This is
useful in case a matching argument is not passed in the function call
statement.
• In a function header, any parameter can’t have a default value unless all
parameters appearing on its right have their default values.
• Example
def interest(principal, time, rate=2)
.
.
.
Si_int =interest(4500,5) # third argument is default value
in function definition.
Identify following headers with default values are legal or illegal

• def interest (prin, rate=9, time)


• # illegal
• def interest (prin =100, rate=9, time)
• # illegal
• def interest (prin, rate=9, time=5)
• # Legal
• def interest (prin =100, rate=9, time=3)
• # Legal
• def interest (prin, time, rate=9)
• # Legal
Keyword (named) Arguments
• These are the named arguments with assigned value
being passed in the function call statements.
• Example
interest (prin=100,time =5, rate =0.5)
interest (rate =0.5, prin=7100,time =2)
interest (time =3, rate =0.2, prin=700)
Using Multiple Argument Types together
• Python allows us to combine multiple argument types in a
function call. Example interest(500,rate=3)
Rules for combing all three types of arguments
• An arguments list must first contain positional arguments
followed by any keyword arguments.
• Keyword arguments should be taken form the required
arguments preferably
• We can’t specify a value for an argument more than once.
Consider the following function header
def interest(prin,cc,time=2,rate=0.09):
return prin*time*rate
Identify following function call statements valid or not
(i) interest(prin=900, cc=5)
Ans. Valid
(ii) interest (rate =0.12,prin=500,cc=4)
Ans. Valid
(iii) interest (cc=4,rate=0.12,prin=500)
Ans Valid
(iv) Interest(5000,3,rate=0.5)
Ans. Valid
(v) Interest (rate=0.5,500,3)
Ans. Invalid - keyword argument before positional argument
(vi) Interest(6500,prin=200,cc=2)
Ans. Invalid –multiple values provided for prin
(vii) Interest(500, principal=900, cc=4)
Ans. Invalid – undefined name used (principal)
(viii) Interest (300,time=2,rate=0.5)
Ans. Invalid – a required argument (cc) is missing
Returning values from functions
(i) non-void function/fruitful function:- The function that return some value(s).
The value being return can be literal, variable and an expression.
(ii) void function:- The function that perform some action or do some work but
do not return any values. If a void function has a return statement then it
takes the following form:
return
Every void function returns value – None.
Example:-
def greet():
print(“Hello”)
a =greet()
print(a)
Output:- Hello
None
Returning multiple values
• To return multiple values from a function, ensure the following
(i) The return statement inside a function body should be of the form
given below:-
return <value1><value2>,…
(ii) The function call statement should receive or use the returned values
in one of the following ways:
(a) Either receive the returned values in form a tuple variable i.e.
def squared(x,y,z) :
return x*x,y*y,z*z
t = squared(2,3,4)
print(t)
(b) Or we can directly unpack the received values of tuple
by specifying the same number of variable
def squared(x,y,z) :
return x*x,y*y,z*z
v1,v2,v3=squared(2,3,4)
print(“The returned values are as follows”)
print(v1,v2,v3)
Composition:- Composition in general refers to using an
expression as part of a larger expression, or a statement as
a part of larger statement.
Scope of Variables
• Scope refers to parts of program within which a variable name
is legal and accessible. Scope rules apply to the
identifier/name labels but not on the values.
Scope of
variable

Global Local
Scope Scope
Global Scope:- A name declared in top level segment (_main_) of
a program and it is usable inside the whole program and all
blocks contained within the program.
• Local Scope:- A name declare in a function body is said to have local scope i.e.
it can be used only within that function/block
• Example
d=5 # global variable
def calsum(a,b,c) : # local variable
s=a+b+c
return s
def average (x,y,z): # local variable
sm=calsum(x,y,z)
return sm/3
num1=int(input(“Number 1”)) # global variable
num2=int(input(“Number2”)) # global variable
num3=int(input(“Number3”)) # global variable
Print(“Average of these number is”, average(num1, num2, num3))
Life time of a Variable
• The time for which a variable name remain in the
memory is called for global variable life time is entire
program run and for local variables is their function run.
Name Resolution (Resolving Scope of a Name)
• Name resolution rule is also known LEGB rule
• Local environment :- It checks within its local environment if it has a
variable with the same name. if not, then it moves to step (ii)
• Enclosing environment :- Python now checks the enclosing environment
if whether there is a variable with same name. If not then it moves to
step (iii)
• Global environment:- Python now checks the Global environment
whether there is a variable with the same name. if not then it moves to
step (iv)
• Built in environment :- Python checks its built in environment that
contain all built in variables and function of python if there is a variable
with the same name; if yes, python uses its value.
To use Global variable inside the local scope
• The global statement is a declaration which hold for the entire current code block. To tell a
function that for a particular name do not create a local variable but use global variable instead.
Syntax
global <variable_name>
example :
def state1 () :
global tigers
tigers =15
print (tigers)
tigers =95
print(tigers)
state1()
print(tigers)

Note :- If same variable name in local scope as well as in global scope, then python uses
local scope instead of global variable.
Mutable/Immutable properties of passed data objects
• If a variable is referring to an immutable type then any change in its value will also change the memory
address it is referring to. Example
def muFunc1(a):
print (“\t Inside myFunc1()”)
print (“\t Value received in ‘a’ as, a)
a=a+2
print (“\t Value of ‘a’ now changes to “,a)
print (“\t returning from myFunc1()”)
num =3
print (“ Calling myFunc1() by passing ‘num’ with value”, num)
myFunc1(num)
print(“Back form myFunc1(). Value of ‘num’ is “, num)
Output : if num=3
Inside myFunc1()
Value received in ‘a’ as 3
Value of ‘a’ now changes to 5 # Value not changes form 3 to 5 inside function
Returning form myFunc1()
If a variable is referring to mutable type then any change in the value of mutable type will not change the memory address of the
variable . Example :
def muFunc2(myList):
print (“\t Inside called function now ”)
print (“\t List received :”, myList)
myList.append (2)
myList.extend([5,1])
print (“\t List after adding some elements: “, myList)
myList.remove(5)
print (“\t List within called function, after all change :”, myList)
return
List1=[1]
print (“List before function call :” List1)
myFunc2(List1)
Print(“\t List after function call :”, List1)
Output:
List before function call : [1]
Inside called function now
List received : [1]
List after adding some elements : [1,2,5,1]
List within called function, after all changes : [1,2,1]
List after function call : [1,2,1] # The value got changed from [1] to [1,2,1] inside function

You might also like