You are on page 1of 33

Working with Functions


Understanding functions:

• The above function can be defined in Python as :

#simple Function
#Function definition
def calc(x): # Function Header
res = 2 * x**2 # Function body
return res
#main program: #Main program
n = int(input("Enter a number : "))
ans = calc(n) # Function call statement/ or invoke function
print("Answer = : ", ans)
Python function types:
• Built-in functions :
• These are predefined functions and always available for use.
For e.g. input(), len(), print(), etc.
• Functions defined in modules :
• These functions are predefined in particular modules and can only
be used when the corresponding module is imported.
For e.g. if you want to use function sin(), you need to import the module math
(that contains definition of the function sin()).
• User Defined Functions:
• These functions are defined as per user requirements.
For e.g. to find the sum of two numbers.
Calling/ Invoking/ Using functions:
• To use the functions, you need to write a function call statement.

A Function call statement takes the following form:


<function name>([<Value(s) to be passed >])
Number of arguments used in function call must be same as the
number of parameters in function definition.
Consider the following function :
#simple Function
def Square(x):
res = x**2
return res
Calling/ Invoking/ Using functions:
• Function’s name is square() and takes one argument.
• The function call statement(s) will be:
• Passing literal as argument in function call
Square(5) # It would pass value 5 to the argument x.
• Passing a variable as argument in function call
A = 15
Square(A) # It would pass variable A to the argument x.
• Taking input and Passing the input as argument in function call
A = int(input(“Enter a number : “))
Square(A) # It would pass variable A to the argument x.
Calling/ Invoking/ Using functions:

• Using function call inside another statement


A = 15
print(Square(A)) # First Square(A) will get computed and then result will be printed.
• Using function call inside expression
A = 15
R = 2 * Square(A) # First Square(A) will get computed and then result will be multiplied by 2.
Defining functions in Python:
A function in Python is defined as per the following format:
def <function name>([parameters]):
[ “ “ “function’s docstring>” “ “ ]
<statement>
[<statement>]
.
.
Structure of a Python program:
• In Python generally all function definitions are given at the
top of the keyword followed by statements which are not
part of any functions.
• These statements are not indented at all. These are often
called from top level statements.
• The Python interpreter starts the execution of a program/
script from the top-level statements.
• The top-level statements are part of the main program.
• Internally Python gives a special name to top-level
statements as __main__.
Structure of a Python program:
#simple Function
def calc(x):
res = 2 * x**2
return res
#main program:
n = int(input("Enter a number : "))
ans = calc(n)
print("Inside function. ",__name__)
print("Answer = : ", ans)
Output:
Enter a number : 5
Inside function. __main__
Answer = : 50
Flow of Execution in a Function Call
• The block is a piece of Python program text that is executed as a
unit (denoted by line indentation).
• A function body is also a block.
• In Python, a block is executed in an execution frame.
• The flow of Execution refers to the order in which statements are
executed during a program run.
• Whenever a function call statement is encountered, an execution
frame for the called function is created and the control(program
control is transferred to it.
• Within the function’s execution frame, the statements in the
function-body are executed, and with the return statement or the
last statement of the function body, the control returns to the
statement wherefrom the function was called.
Flow of Execution in a Function Call
In a Program,

• Execution always starts at the first statement of a program.


• Comment lines are ignored.
• If Python notices that it is a function definition, just executes the
function header and skips all lines in the function body.
• In Python a function can define another function in it. But since the
inner function definition is inside a function-body, the inner definition
isn’t executed until the outer function is called. When a code line
contains a function-call, Python first jumps to the function header line
and then executes to the function body.
• A function ends with a return statement or the last statement of the
function body, whichever occurs earlier.
• If a called function returns a value then the control will jump back to
the function call statement and completes it.
• If a called function does not return any value, then the control jumps
back to the line following the function call.
Arguments and Parameters:
• Parameters: Values being received in function definition. i.e.
name within function definition.
• Arguments: Values passed when the function is function
called.
• Arguments in Python can be one of these value types:
* Literals * variables * expressions
• The alternative names for argument are actual parameter and
actual argument.
• The alternative names for parameter are formal parameter
and formal argument.
Passing Parameters:
• Python supports three types of formal arguments /
parameters:
1. Positional arguments (Required arguments)
2. Default arguments
3. Keyword (or named) arguments
1. Positional arguments (Required arguments)

• Through function calls:


• The arguments must be provided for all parameters
(Required)
• The values or arguments are matched with parameters,
position (order) wise (positional)
• This way of parameter and argument specification is
called Positional arguments or Required arguments or
Mandatory arguments as no value can be skipped from
the function call or you can not change the order.
2. Default arguments :
• Python allows to assign default value(s) to function’s parameters which
is useful in case a matching is not passed in the function call statement.
• The default values are specified in the function header of function
definition.
• Non-default arguments cannot follow default argument.
• (In a function header, any parameter cannot have default value unless
all parameters appearing its right have default value.)
• A parameter having default value in the function header is known as a
default parameter.
• A parameter having a default value in function header becomes
optional in function call.
• The default values for parameters are considered only if no value is
provided for that parameter in the function call statement.
Default arguments :
• A function call may or may not have value for it.

For e.g.

def test(a, b, c=5):

function call can be :

test(10, 17) then a will have value 10, b will have 17 and c will have value 5
test(10, 17,100) then a will have value 10, b will have 17 and c will have value 100
3. Keyword (Named) arguments
• To have complete control and flexibility over the values sent
as arguments for the corresponding parameters, Python
offers another type of argument Keyword (Named)
arguments.
• Keyword arguments are the named arguments with
assigned values being passed in the function call statement.
• You can write any argument in function call statement in any
order provided you name the arguments when calling the
function.
Keyword (Named) arguments
The output :
For eg.
Output -1 test(x, y, z)
#Keyword arguemnts
a = 10
def test(a, b, c):
b = 20
print("a = ",a)
c = 30
print("b = ",b) Output -2 test(c = 7, a = 14, b = 45)
print("c = ",c) a = 14
x = 10 b = 45
y = 20 c= 7
z = 30 Output -3 test(c = y, a = z, b = x)
print ("Output -1 ", "test(x, y, z)") a = 30
test(x, y, z) b = 10
print ("Output -2 ", "test(c = 7, a = 14, b = 45)") c = 20
test(c = 7, a = 14, b = 45)
print ("Output -3 ", "test(c = y, a = z, b = x)")
test(c = y, a = z, b = x)
Using Multiple types of arguments:
• Python allows you to combine multiple types of
arguments:
• Rules for combining all types of arguments:
• An argument list must first contain positional arguments
followed by any keyword argument.
• Keyword arguments should be taken from the required
arguments preferably.
• You cannot specify a value for an argument more than
once.
Returning values:

• Functions in Python may or may not return a value.


• There can be two types of functions in Python:

• Functions returning some value (non-void function)


• Functions not returning any value (void function)
Returning values:
Functions returning some value (non-void function)
The computed value is returned using return statement from this
type of functions:
Syntax :
return <value>
The value being returned can be one of the following:
-A literal - a variable - an expression
For e.g.
return x + y

while invoking function,


we write as :
result = calc(3,5) returned value from the calc() will replace this function call
Returning values:
• Functions returning some value (non-void function)
• The returned value will internally substitute the function call
statement.
• The returned value of a function should be used in the caller function/
program inside an expression or a statement .
For e.g.
Result = calc(3,5)
print(calc(3,5))
calc(3,5)<5
• If you do not use their value in any of these ways and just write a
stand-alone function call, Python will not report an error but their
return value is wasted.
• Functions returning a value are also known as fruitful functions.
• The return statement ends function execution even if it is in the
middle of the function.
Returning values:
• For e.g.
• Functions not returning any value
def replicate():
(void function) print(“$$$$$”)
• The functions that performs some action or do
some work but do not return any computed value print(replicate())
or final value to the caller are called void functions. output:
• A void function may or may not have a return $$$$$
statement.
None
• If a void function has a return statement, then it
has the following form :
return def replicate():
• That means, a keyword return without any value or return “$$$$$”
expression. print(replicate())
• Every void function returns value none to its caller. output:
$$$$$
Returning values:

• Functions not returning any value (void function)

In Python, you can have following combinations of functions:

• Non-void functions without any arguments.


• Non-void functions with some arguments.
• Void functions without any arguments.
• Void functions with some arguments.
Returning values:
• Returning multiple values:
• Unlike other programming languages, Python lets you return multiple
values from a function.
• To return multiple values from the function, ensure the following
things:
• The return statement inside a function body should be of the form
given below:

return <value1/variable1/expression1>, <value2/variable2/expression2>, …

• The function call statement should receive or use the returned values
in one of the following ways:
• Either receive the returned values in form of tuple variable.
Returning values:
• Returning multiple values:

def squared(x,y,z):
return x*x, y*y, z*z
t = squared(2, 3, 5)
print(t) # output will be printed as : (4, 9, 25)

You can directly unpack received values of tuple by specifying the same
number of variables on the left-hand side of the assignment in function
call, e.g.

def squared(x,y,z):
return x*x, y*y, z*z
a, b, c = squared(2, 3, 5)
print(a, b, c) # output will be printed as : 4, 9, 25
Composition:
• Using an expression as a part of larger expression.
Scope of variables:
• Scope of a variable means part(s) of a program in which
variable is accessible.

• Types of scope in Python:


• Local variable
• Global variable
• Local variable –accessible only inside the functional block where
it is declared.
Scope of variables:
• Local variable –
accessible only inside the functional block where it is declared.

For e.g.
def test_fun():
x = 10
print(“value of x inside function : ", x)
Here, x is a local variable.
Scope of variables:
Global variable :
variable which is accessible among whole program using global
keyword.
Non local variable –accessible in nesting of functions, using nonlocal
keyword.
x=5
def test_fun():
global x
x = 10
x=x+1
print("Global value inside function : ", x)
x = x**2
print("Value before function call : ",x)
test_fun()
print("Value after function call : ",x)
Functions using libraries:
• Mathematical, and string functions.
• Mathematical functions:
• Mathematical functions are available under math module. To use
mathematical functions under this module, we have to import the
module using the command :
import math
For e.g.
To use sqrt() function we have to write statements like given below.

import math
x = math.sqrt(4)
print(x)
output will be 2
Functions using libraries:

String functions:
• String functions are available in python standard module.
These are always available to use.
• For e.g. capitalize() function converts the first character of
string to upper case.

You might also like