0% found this document useful (0 votes)
59 views36 pages

XII WorkingWithFunction

The document discusses functions in Python. It explains what functions are, how to define functions, call functions, and pass parameters to functions. It also covers built-in functions, functions from modules, and user-defined functions.

Uploaded by

Lakshya Nayak
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)
59 views36 pages

XII WorkingWithFunction

The document discusses functions in Python. It explains what functions are, how to define functions, call functions, and pass parameters to functions. It also covers built-in functions, functions from modules, and user-defined functions.

Uploaded by

Lakshya Nayak
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/ 36

Working with Functions

in Python

Raja Malviya, PGT-Computer Science,Jawahar Navodaya Vidyalaya, Badi, Raisen(M.P.)


Working with Function
• Large programs generally avoided because it is difficult to mange a single list of
instruction.
• For that, large program is broken down into smaller units known as Function.
• Function make a program more readable and understandable to a programmer
thereby making program management much easier.
• Function is a subprogram that acts on data and often returns a value.
Understanding Functions
Let a mathematical function f(x) = 2x2 can Here,
be written in Python as :  def mean a function, and calcsomething is the function name.
 variable/identifiers inside the parentheses are the arguments or
def calcsomething(x): parameters(value given to function).
r=2*x**2  In the given function x is the argument.
return r  The colon(:) at the end of def line , meaning it require a block
 the statements indented below the functions, define the
functionality(working) of the function.
 This block is also called the body-of-the-function.
 The return statements return the computed result.
Calling/Inworking/Using a Functions
• A function call statement takes the following form:
<function-name>(<value-to-be-passed-to-argument>)
Example
calcsomething(5) # value 5 is being sent as argument

Another function call for the same function, could be written as :


a=7
calcsomething(a) #this time variable a is being sent as argument
Calling/Inworking/Using a Functions
i) Passing literal as argument in function call
cube(5)
ii) Passing variable as argument in function call
The syntax of the function
a=7 call is very similar to that
of the declaration, except
cube(a) that the key word, def and
colon(:) are missing
iii) Taking input and passing the input as argument in function call
mynum=int(input(“Enter a number”))
cube(mynum)
iv) Using function call inside another statement
print(cube(3))
v) Using function call inside another statement
DoubleOfcube=2*cube(6)
Python Functions Types
• Functions can be categorized as belonging to
• Built in functions
• Function defined in modules
• User Defined functions
Built in Functions
• Built in functions are the function(s) that are built into Python and can be
accessed by Programmer.
• We don't have to import any module (file).
• Python has a small set of built-in functions as most of the functions have been
partitioned to modules. This was done to keep core language precise.
• abs() max() min() bin() divmod() len() range() round() bool() chr() float() int()
long() str( ) type( ) id( ) tuple( )
Function defined in modules
• A module is a file containing Python definitions (i.e. functions) and statements.
• Standard library of Python is extended as module(s) to a Programmer.
• Definitions from the module can be used into code of Program.
• To use these modules in a program, programmer needs to import the module.
Once we import a module, we can reference (use) to any of its functions or
variables in our code. There are two ways to import a module in our program,
they are
• import
• from
Function defined in modules[import]
• Import: It is simplest and most common way to use modules in our code.
Syntax:
• import modulename1 [, module name 2, ---------]
Example: Input any number and to find square and square root.
Example:
import math Output:
x = input ("Enter any number") Enter any number25
y = math.sqrt(x) Square Root value= 5.0
a = math.pow(x,2) square value= 625.0
print "Square Root value=",y
print "square value=",a
Function defined in modules[from]
• From statement: Used to get a specific function in the code instead of complete file.
• If we know beforehand which function(s), we will be needing, then we may use 'from'. For
modules having large number of functions, it is recommended to use from instead of
import.
Syntax
>>> from modulename import functionname [, functionname…..]
from modulename import *
will import everything from the file.
Example: Input any number and to find square and square root.
Example: Output:
from math import sqrt,pow
x=input("Enter any number") Enter any number 100
y=sqrt(x) #without using mathSquare Root value = 10.0
a=pow(x,2) #without using mathsquare value = 10000.0
print "Square Root value =",y
print "square value =",a
User Defined Functions
• In Python, it is also possible for programmer to write their own function(s).
• These functions can then be combined to form module which can be used in other programs
by importing them.
• To define a function, keyword 'def' is used.
Syntax:
def NAME ([PARAMETER1, PARAMETER2, …..]):
#Square brackets include optional part of statement
statement(s)
Example: To find simple interest using function.
Example: Output:
def SI(P,R,T): >>> SI(1000,2,10)
return(P*R*T) 20000
User Defined Functions [Parameters and Arguments]
• Parameters are the value(s) provided in the parenthesis when we write function header.
• If there is more than one value required by the function to work on, then, all of them will be
listed in parameter list separated by comma.
Example: def SI (P,R,T):
• Arguments are the value(s) provided in function call/invoke statement.
• List of arguments should be supplied in same way as parameters are listed.
Example: Arguments in function call
>>> SI (1000,2,10)
1000,2,10 are arguments. An argument can be constant, variable, or expression.
Example: Write the output from the following function: Output
def SI(p,r=10,t=5): >>> SI(10000)
return(p*r*t/100) 5000
if we use following call statement: >>> SI(20000,5)
SI(10000) 5000
SI(20000,5) >>> SI(50000,7,3)
SI(50000,7,3) 10500
Defining Function in Python
Structure of a Python Program
• In a Python program, generally all function definition are given at the
top followed by statements which are not part of any functions.
• These statements are not indented are not indented at all.
• These are often called from the top-level statements.
• The top-level statements are part of the main program.
• Python gives a special name to top-level statements as __main__
Example Output
def greet(): at the top most levle right now
print("hi...hello") inside __main__
print("at the top most levle right now")
print("inside",__name__) Notice word ‘__main__’
is the output by Python
interpreter
Flow of Execution in a Function Call
• The Flow Of Execution refers to the orderin which statements are
executed during a program run.

Note: The function calling another function is called the caller and the function being called
is the called function(or callee). Here, the __main__ is the caller of func() function.
Arguments and Parameters
Example  We see that there are values being passed
def multiply(a, b): (through function call) and values being
received (in function definition)
print(a*b)
 Arguments: Python refer to the values being
y=3 passed as arguments.
multiply(12, y)  Parameters: values being received as
multiply(y, y) parameters
Parameter or formal
multiply(y, x) parameter

Arguments or actual
arguments

Note: The values being passed through a function call statement are called arguments(or
actual parameters or actual arguments). The values received in the function
definition/header are called parameter or formal parameter or formal arguments)
Passing Parameters
Python supports three types of formal parameters:
1. Positional arguments(Required arguments)
2. Default arguments
3. Keyword( or named ) arguments
Positional Arguments(required arguments)
If a function definition header is like:
def check(a, b, c):

then possible function calls for this can be :


check(x, y, z) # 3 values (all variables) passed
check(2, x, y) # 3 values (literal + variables) passed
check(2, 5, 7) # 3 values (all literals) passed
Note:
When the function call statement must match the number and order of
arguments as defined in the function definition, this is called the positional
argument matching.
Default Arguments
Python allows us to assign default values(s) to a function’s parameter(s) which is useful
in case a matching argument is not passed in the function call statement.
The default values are specified in the function header of function definition.
def interest(principal, time, rate=0.10):

This is default values for parameter rate. If in a


function call, the alue for rate is not provided , Python
will fill the missing value(for rate only) with this value.

si_int=interest(5400,2) # third argument is missing


i.e. value 5400 is passed to principal, the value 2 is passed to the parameter time and
the third argument rate will have default value 0.10
si_int=interest(6100, 3, 0.15) # no argument is missing
i.e. the parameter principal will gets 6100, time gets 3 and rate gets value 0.15
Default Arguments
Note:
In a function header , any parameter cannot have default value unless all parameter
appearing on its right have their default values.
Example:

def interest(prin, time, rate = 0.10) : legal


def interest(prin, time=2, rate) : Illegal (default parameter before required parameter)
def interest(prin=2000, time,=2 rate) : Illegal (default parameter before required parameter)
def interest(prin, time=2, rate = 0.10) : legal
def interest(prin = 200, time=2, rate = 0.10) legal
:
Keyword (Named) Arguments
Note:
Python offers a way of writing function calls where we can write any argument in any
order provided you name the arguments when calling function as shown below:
Example:

interest(prin=2000, time=2, rate = 0.10) : Here, prin gets value 2000, time gets value as 2 and rate as 0.10
interest(time=4, prin=2600, rate = 0.09) : Here, prin gets value 2600, time gets value as 4 and rate as 0.09
interest(time=2, rate = 0.12, prin=2000,) : Here, prin gets value 2000, time gets value as 2 and rate as 0.1
Using Multiple Argument Types Together
Example: The first argument value (5000) in above statement is representing a positional argument as
it will be assigned to first parameter on the basis of its position.
interest(5000, time = 5)
The second argument value (time = 5) in above statement is representing keyword argument or
named argument.
Rules for combining all three types of arguments
• Python states that in a function call statements:
• An argument list must first contain positional (required ) arguments followed by any keyword argument.
• Keyword arguments should be taken from required arguments preferably.
• You cannot specify a value for an argument more than once.

Example, let a function header:


def interest(prin, cc, time = 2, rate = 0.09):
return prin*time*rate
It is clear from above function definition that values for parameter prin and cc can be provided either
as positional arguments or as keyword arguments but these values cannot be skipped from the function
call.
Using Multiple Argument Types Together

Note: Having a positional arguments after keyword arguments will result into error.
Returning Values From Functions
• Functions in python may or may not return a value.
• There can be broadly two types of functions in Python:
 Function returning some values (non-void functions)
 Functions not returning any value ( void function)

a) Function returning some values (non-void functions)


Syntax :
The value being returned can be any one of them from a literal, variable or an expression.
return<value>

return 5 # literal being returned

return 6+4 # expression involving literal being returned

return a # variable being returned

return a**3 # expression involving variable and literal, being returned

return (a+8**2)/b # expression involving variables and literals, being returned

return a+b/c # expression involving variables being returned


Returning Values From Functions
[Important]
Returning Values From Functions
b) Function not returning any values (void functions)

Note: A void function (some times called non-fruitful function) returns legal empty value
of Python i.e. None to its caller.
Returning Multiple Values
To return multiple values from a function, we have to ensure following
things:
i) The return statement inside a function body should be of the form
given below:
return <value1 / varable1 / expression1>, <value2 / varable2 /
expression2>,……..
ii) The function call statement should receive or use the returned value
in one of the following ways:
Returning Multiple Values
ii) The function call statement should receive or use the returned value in one of the
following ways:
COMPOSITION
 Composition in general refers to using an expression as part of a larger
expression or
 Statement as a part of larger statement
 An arithmetic expression e.g.
greater((4+5),(3+4))
 A logical expression e.g.
test(a or b)
 A function call (function composition) e.g.
int(str(52))
int(float(“52.5”)*2)
int(str(52) + str(10))
Scope of variables
• Two kinds of scopes in Python are
1. Global Scope
 A name is declared in top level segment( __main__) of a program is
said to have a global scope and is usable inside the whole program
and all blocks(functions, other blocks) contained within the program.
2. Local Scope
 A name declared in a function-body is said to have local scope i.e.
it can be used only within this function sand the other blocks
contained under it.
 The names of formal arguments also have local scope.
Scope Example 1
1. def calcSum (x, y):
2. z=x+y
3. return z
4. num1 = int(input(“enter first number:”))
5. num2 = int(input(“Enter second number :”))
6. Sum = calcSum(num1, num2);
7 print(‘sum of given number is’, sum)

 In the above program there are three variables num1, num2 and sum defined in the
main program and three variables x,y and z defined in the function calcSum().
 num1,num2 and sum are global variables and x,y and z are local variables( local to
function calcSum() ).
Scope Example 1
Scope Example 1
Scope of variables
Variable defined outside all functions are global.
Example
x=5
def func(a) :
b=a+1 Variables x defined above all functions. It is also a global variable
return b along with y and z.

y = input(“Enter number”)
z = y + func(x)
print(z)
Name Resolution(Resolving Scope of a Name)
Python follow NAME Resolution Rule, also known as LEGB rule.
 L. Local - It first makes a local search Example:
i.e. in current def statement. The import x=5
statements and function definitions bind def func1():
x=2
the module or function name in the local
x=x+1
scope. In fact, all operations that
def func2():
introduce new names use the local global x
scope. x=x+1
 E. Enclosing functions - It searches in print x
all enclosing functions, form inner to func1()
outer. print x
 G. Global (module) - It searches for func2()
global modules or for names declared print x
global in a def within the file. The above example prints 5; then calling
 B. Built-in (Python) - Finally it checks func1()it prints 3. This is because func1 only
for any built in functions in Python. increments a local x. Then func2() increments
the global x and prints 6.
Thanks to all……

You might also like