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

functions

Uploaded by

pawansaxena1980
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

functions

Uploaded by

pawansaxena1980
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 51

Unit I: Computational Thinking and Progamming-2

FUNCTIONS
 Introduction to functions
 Function scope
 Parameter passing
 Mutable/Immutable properties of data objects
 Passing strings, lists, tuples, dictionaries to functions
 Default parameters, Positional parameters
 Return values
 Functions using libraries: mathematical and string
functions.
 INTODUCTION TO
FUNCTIONS

 ADVANTAGES OF
FUNCTIONS

 TYPES OF FUNCTIONS IN
PYTHON
What is a FUNCTION?
 A function is a programming block of codes
which is used to perform a single, related task.
 It only runs when it is called.
 We can pass data, known as parameters, into a
function.
 A function can return data as a result.
 We have already used some python built in
functions like print(),etc.
But we can also create our own functions.
These functions are called user-defined functions.
Example: Let us consider a big main program BANK where multiple functional
departments acts as sub-functions of the BANK. Each sub-functional department is
independent on its own which makes the work of entire BANK easy, faster. If any
problem arises in a particular sub-functional department, it is capable of testing the
problem itself and overcome from the situation. Every department is easily
identifiable by their name like Loan, Insurance, Fund management etc. can be used
again and again by same or different customers. Hence, different sub-functional
departments increases efficiency of the BANK.
Thus, the same fundamental concept can be applied to FUNCTIONS in PYTHON.
Advantages of Using Functions /
User-defined Functions:
1.Program development made easy and fast :
Work can be divided among project members thus implementation can
be completed fast.
2.Program testing becomes easy :
Easy to locate and isolate a faulty function for further investigation
3. Code re-usability increases :
A function can be used to keep away from rewriting the same block of
codes which we are going use two or more locations in a program. This is
especially useful if the code involved is long or complicated.
4.Increases program readability :
It makes possible top down modular programming. In this style of
programming, the high level logic of the overall problem is solved first
while the details of each lower level functions is addressed later. The length
of the source program can be reduced by using functions at appropriate
places.
TYPES OF FUNCTIONS
USER
DEFINED
FUNCTIONS

BUILT-IN-FUNCTIONS

LAMBDA FUNCTIONS

RECURSION FUNCTIONS
TYPES OF FUNCTIONS
Definition of FUNCTIONS with example
USER-DEFINED FUNCTIONS: Functions that we define ourselves to do certain specific task are
referred as user-defined functions. In Python, a user-defined function's declaration begins with the
keyword def and followed by the
function name and parenthesis () .
Eg.Creating a user-defined function
to calculate area of a square
OUTPUT

BUILT-IN FUNCTIONS
Built-in functions are those that are already defined in Python libraries and we can call them directly.
Eg. Pop() function in List, math.sqrt() function from math library, random.randint()
function from random module, str.isupper() function for strings etc.

LAMBDA FUNCTIONS
In Python, a lambda function is a single-line function declared with no name,
which can have any number of arguments,but it can only have one expression.

RECURSION FUNCTIONS
Recursive function means that the
function will continue to call itself
and repeat its behaviour until some
condition is met to return a result. OUTPUT
USER DEFINED
FUNCTIONS
ACTUAL AND
FORMAL
PARAMETERS
PARAMETER PASSING
SYNTAX OF USER-DEFINED FUNCTION
A function once defined can be called/invoked as many times
as needed by using its name, without writing its full code
again and again.
A function in Python is defined as per the following SYNTAX :
def <function name> ([Parameters]):
[ “ “ “ <function’s docstrings>” ” ” ]
<statement>
[<statement>]
…..
…..

SYNTAX  rules of writing a program


• Item(s) inside angle brackets < > has to be provided by the programmer
• Item(s) inside square brackets [ ] is optional, i.e., can be omitted
• Item(s)/ words/ punctuators outside < > and [ ]have to be witten as specified.
USER DEFINED FUNCTIONS
FUNCTION DEFINITION STATEMENT # FUNCTION DEFINITION
To define a function keyword def is used.
After the keyword comes an identifier i.e.
name of the function, followed by # BLOCK / BODY
parenthesized list of parameters and the OF FUNCTION
colon which ends up the line. Next
follows the block of statement(s) that are
the part of function.
BLOCK / BODY OF THE FUNCTION # MAIN PROGRAM BEGINS HERE
A block is one or more lines of code,
grouped together so that they are treated
as one big sequence of statements while
executing. Statements in a block are
written with indentation. All the
FUNCTION CALL
statements of the block should be at same
indent level. A function may or may not
have return statement.
FUNCTION CALL / INVOKE
Function Call is a statement that executes a
function. It consists of the name of the
OUTPUT
function being called ,followed by a list of
arguments enclosed in parentheses ( ).
Arguments are optional
USER DEFINED FUNCTIONS :
LINE NUMBERS Flow of Control / Execution

FLOW OF EXECUTION Inside function

(As per the Lines on the Line number) 16712378


NOTE: Line 4 is blank and Line 5 is a comment statement which is ignored
NOTE: Before entering the Main part of the program, the control gets to know that
a function named area is defined here, which will be called/invoked later. Similarly, if
there are many functions then the CONTROL goes though the Function Definition 1st
Line of all the functions starting from top. EXECUTION begins from MAIN
USER DEFINED FUNCTIONS :
LINE NUMBERS Flow of Control / Execution

FLOW OF EXECUTION
OUTPUT Inside function

1561237
NOTE: Line 4 is a comment statement
which is ignored
NOTE: Before entering the Main part of the program, the control gets to know that
a function named wishes is defined here, which will be called/invoked later. Control
comes to Line 7 after execution of the body(Line 2,3) of the function and NOT is Line
no. 6 as there is NO RETURN statement. Control of execution jumps back to the line
following the function call.
FUNCTION CALL/INVOKE
To use a function that has been defined earlier, we need to write a function call
statement.

SYNTAX: <function_name>(<value to be passed to argument>)

OUTPUT

OUTPUT
Example of different ways of FUNCTION CALL/INVOKE
NOTE: The syntax of the function
call is very similar to that of the
function declaration, except that the
keyword def and colon : are missing

Here, Add() is the name of the user-defined function. It has been called in 5 ways, by sending
5 different kinds of arguments used in Function call statements, which are:
FUNCTION CALL 1 Passing literals FUNCTION CALL 4 taking input and passing it
FUNCTION CALL 2Passing fixed value FUNCTION CALL 5Function call inside expression
FUNCTION CALL 3 Passing variable
STRUCTURE OF A PYTHON PROGRAM: Top Level Segment
__main__
• Generally, all function definitions are given at the top followed by statements which
are not part of any functions and these statements are not indented at all. These
statements are called as top-level statements (which are without indentation).
• The Top-level statements are part of the main program from where the interpreter
starts the execution of a program/script.
• Internally, Python gives a special name to top-level statements as __main__
• Python stores this name in a built-in variable called __name__ ( we do not need to
declare this variable, we can directly use it)
POINTS TO REMEMBER:
Actual Flow of Execution in Programs with Functions
• Execution always begins at the first statement.
• Comments are not executed.
• If the control of the Python interpreter notices a function definition, (def
statements) then Python executes just the function header line and skips all lines
in the function body.
• The statements inside function-body are not executed until the function is called.
• When a code line contains function-call, Python first jumps to the function header
line and then executes the statements inside the function-body.
• A function ends with a return statement or the last statement of function body,
whichever occurs earlier.
• If the called function
– Does not return any value i.e., the return statement has no variable o value o expression, then
the control jumps back to the line following the function call.
e.g., wishes() function in previous slides without return statement.
– Returns a value i.e. has a statement like return <variable/value/expression>
(e.g., return s or return 22/7 or return p+q) then the control will jump back to the
function call statement and completes it (e.g., if the returned value is to be assigned to
variable or to be printed or to be compared or used in any type of expression.)
e.g., Add() function in previous slides with return statement return s
ARGUMENTS and PARAMETERS

Values (Variables/Literals/Expressions) being passed from the


Function-Call statement are known as ARGUMENTS / ACTUAL
ARGUMENTS/ACTUAL PARAMETERS
The Values received (Variables/Names) in the Function-Definition /
Function Header statement are known as PARAMETERS /
FORMAL PARAMETERS /FORMAL ARGUMENTS.

NOTE: MATCH THE NO. OF ARGUMENTS WITH NO. OF PARAMETERS


Function-Call must send all the ACTUAL ARGUMENTS as required by the Function
Definition Header’s FORMAL PARAMETERS
For e.g., if a Function-Definition Header has three parameters then the Function-Call
must send three arguments/values.
ARGUMENTS and PARAMETERS Example
Here, x and y are FORMAL PARAMETERS
ACTUAL ARGUMENTS

In First Function call ,x and y takes 5 and 2 values in Function header 5-2 =3

In Second Function Call, x takes value of a, y takes value 3 in Function header


Hence, 7-3 = 4

In 3rd Function Call, x takes value n*3=10*3=30, and y takes value of n=10 ,
hence, 30-10 = 20

OUTPUT
ARGUMENTS and PARAMETERS contd..

NOTE: Syntax Error occurs if the Formal parameters


have expressions.
FORMAL PARAMETERS can have just names or
variables i.e. any identifiers to hold the incoming
value from the Function-Call by ACTUAL ARGUMENTS
FUNCTION CALL mechanism in In PYTHON Programming language
C,C++ programming language
 CALL BY VALUE  Immutable data types (like
The called function makes a separate copy stings,numbers etc.) implement CALL
of the passed values and then works with them, BY VALUE mechanism funda.
so original values remain unchanged .
 CALL BY REFERENCE
 Mutable data types (like List,
The called function works with the original
Dictionaries) implement CALL BY
values passed to it, thus any changes made to it,
REFERENCE mechanism funda.
takes place in the original values only.
PASSING PARAMETERS
Python supports three types of FORMAL
arguments/parameters:

i. Positional / Required / Mandatory


arguments

ii. Default arguments

iii. Keyword (or Named arguments)


PASSING PARAMETERS: Positional / Required / Mandatory arguments
 When the function call statement must match the number and order of arguments as defined
in the function definition. 1st parameter receives the value of 1st argument, 2nd parameter
receives the value of 2nd parameter and so on…
 They are also known as Required / Mandatory arguments as no value can be skipped from
the function call or we cannot change the order. E.g. we cannot assign value of first argument
to third parameter.

Function Call 1 Output= (8+6)-4=10


Function Call 2 Output= (8+20)-5=23
Function Call 3 Output= (70+40)-25=85

Function Call 4: Error


PASSING PARAMETERS: DEFAULT arguments
ii) Default arguments
 A parameter having default value in the function header is known as
DEFAULT parameter.
 Default values are specified in the function header.
 Non-default arguments cannot follow Default argument.
 A parameter having a Default value in function header becomes optional
in function call.
 Function call may or may not have value for it.
The Default values for parameters are considered ONLY if no value is
provided for the parameter in the function call statement.
In a function header, any parameter cannot have a default value unless
all parameters appearing on its right have their default values.
Default arguments are useful in situation where some parameters always
have the same value.
Default arguments give flexibility to a program.
ADVANTAGES: of Default Arguments
They can be used to add new parameters to the existing functions
They can be used to combine similar functions to one.
PASSING PARAMETERS: DEFAULT arguments
Default
value is 10
which is used
in absence of
Call 1 Output= (30+20)-10=40
actual
Call 2 Output= (30+20)-5=45 parameter for
the formal
Call 3 Output= (70+40)-25=85
arguments
Call 4 Output= (50+30)-10=70 having default
value
In Call 1, x and y gets value of a and b
respectively. z takes default value as 10 since, no
value is given in function call for z.
In Call 2 and Call 3 , z takes the values 5 and 25
respectively , which are given in Function Call
statements.
In Call 4, x and y takes 44,24 values respectively
and z takes Default value as 10

Function Call 5: Error as


the middle argument
has not been assigned
any default value.
Calculation of Simple Interest.
We know,
#Without Default values
Simple Interest=
principal*time*rate/100
Here, Variable p for principal
Variable t for time
Variable r for rate
Function name simple_interest

VALID for Function CALL 1 and CALL 2

VALID for CALL 1, CALL 2 and CALL 3


VALID for CALL 1, CALL 2,CALL 3,CALL 4

# INVALID Function calls


because default parameters
appeared before
required/mandatory
arguments.
PASSING PARAMETERS: KEYWORD / NAMED arguments
iii) Keyword (or Named arguments)
 Keyword arguments are the named arguments with assigned values
being passed in the function call statement.
 We can write any argument in any order provided we name the
arguments when calling the function.

OUTPUT
The values of p, t, r are taken as per the named variables
which are sent from the function call arguments as actual
arguments to the formal parameters in function header.
PASSING PARAMETERS:
USING MULTIPLE ARGUMENT TYPES TOGETHER
RULES FOR COMBINING ALL THREE TYPES OF
ARGUMENTS : (Priority wise)

1. positional, 2. keyword, 3.default

Python states that in a function call statement:


i. An argument list must first contain positional(required)
arguments followed by any keyword argument.
ii. Keyword arguments should be taken from the required arguments
preferably
iii. Specifying a value for an argument more than once is NOT allowed.
Only once an argument should get a value in a function call.
PASSING PARAMETERS:
USING MULTIPLE ARGUMENT TYPES TOGETHER Example:
Here, principal, p is
given as the
positional argument
as it gets the fist
value 4000
according to its
position in the call.
Time ,t=6 is the
keyword argument,
which is given by the
name t. ate, gets
the default
argument as 5 from
OUTPUT  4000*6*5/100=1200 the function
definition header.

Positional arguments
after keyword
arguments will result
into error !!!
RETURN
STATEMENTS
(returning single value
and multiple values)
RETURNING VALUE FROM FUNCTIONS
In Python,

FUNCTIONS can be broadly classified as:


1. Functions RETURNING SOME VALUE
(non-void functions / Fruitful functions)
• Non-void functions without any arguments
• Non-void functions with some arguments

2. Functions NOT RETURNING ANY VALUE


(void function)
o Void functions without any arguments
o Void functions with some arguments
FUNCTIONS RETURNING SOME VALUE
(non-void functions)
• The functions that return some computed result in terms of a
value are considered as non-void functions.
SYNTAX
return <value>
The value returned can be one of the following:
 A literal
 A variable
 An expression
Eg. of some legal return statements:
return 10 //LITERAL returned
return 15+6 //EXPRESSION with LITERALS returned
return z //VARIABLE returned
return z**5 //EXPRESSION with VARIABLE and LITERAL returned
return (a+ 10**3)/z //EXPRESSION with VARIABLE and LITERAL returned
return p-q*r //EXPRESSION with VARIABLES only returned
IMPORTANT Note on RETURN:
The value which is returned to the CALLER function/ Program should
be used inside an expression or a statement.

COMMENTS given
here are self-
explanatory!!

OUTPUT
IMPORTANT Note on RETURN contdd.:
Here, return statement is at the
end of the function body and
hence, gives a proper output.

OUTPUT
Here, return statement has ignored Here, there is NO return
the else part. So, before completion statement. Function
of the execution of the function without any return
body, the Return statement gets
executed. Hence, output is
statement, actually
IMPROPER. This function is similar returns None literal.
to a function without any return None denotes a special
statement. object Nothing (a legal
empty value).

OUTPUT OUTPUT
Non-void functions (Functions returning some values)
Non-void functions without any arguments Non-void functions with some arguments
1 1

2
2

3 OUTPUT
3 OUTPUT
printed here printed here

OUTPUT OUTPUT

Void functions (Functions NOT returning any value)


Void functions without any arguments Void functions with some arguments
1 1 OUTPUT
2 printed here
2 OUTPUT
printed
here

3 3
OUTPUT OUTPUT
Here, in absence of the return statements in the body of the function, the control comes back to the next statement of
the Function Call. Program stops if there is no such statement after Call.
RETURNING MULTIPLE VALUES from a FUNCTION
If you have ever learnt any other programming language, then you must
have seen that function returns one single value which is not in the case of
Python Programming language. In Python, to return multiple values from a
function, the following must be observed:
i) The return statement inside a function body should be of the form
given below:
return <value1 / variable1 / expession1>,<value2 / variable2 / expession2>,… so on
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 b) Or directly unpack the received values of tuple by
form of a tuple variable: specifying the same number of variables on the
left-hand side of the assignment in function call.
FUNCTION SCOPE :
Local and Global Scope
LOCAL AND GLOBAL
VARIABLE
LIFETIME of a Variable
NAMESPACE RESOLUTION
FUNCTION SCOPE
SCOPE of a Variable: Part of a program within which a name is legal(or
known) and accessible (can be used), is called the SCOPE of a variable.

LIFETIME of a Variable: The time for which a variable or name


remains in the memory is known as LIFETIME of a variable.
There are two types of variables with the view of scope.
Local variable Global variable
DEFINITION: It is a variable which is DEFINITION: It is a variable which is
declared within a function or within a declared outside all the functions and
block and accessible only within the accessible to the whole program using
function/block. global keyword.
It is accessible only within a It is accessible throughout the program.
function/block in which it is declared.
Lifetime of a LOCAL variable is, as long Lifetime of a GLOBAL variable is it’s entire
as the Function runs in the memory. program run ( i.e. the GLOBAL variables
live in the memory as long as the Program
is running.
Example on GLOBAL and LOCAL variables

OUTPUT
NAME RESOLUTION (Resolving Scope of a variable/name) :
LEGB Rule
For every name reference or a variable within a program
i.e. when we access a variable from within that function,
4 Python follows the LEGB Name Resolution Rule to resolve :

i) Python Checks within its LOCAL


3 Environment if it has the same name ; if
Yes, Python uses its value. If Not, then it
moves to step (ii).

2 ii) Python Checks the ENCLOSING


Environment if it has the same name ; if
Yes, Python uses its value. If Not, then it

1 moves to step (iii).


iii) Python Checks within its GLOBAL
Environment if it has the same name ; if
Yes, Python uses its value. If Not, then it
moves to step (iv).
iv) Python Checks within its BUILT-IN
Environment if it has the same name ; if
Yes, Python uses its value.
v) If Not, then Python repots ERROR.
Understanding LEGB Rules with Examples

OUTPUT

OUTPUT
Understanding LEGB Rules with Examples contd..

OUTPUT

OUTPUT
Understanding LEGB Rules with Examples contd..
Using GLOBAL VARIABLE inside LOCAL SCOPE
• The Global statement is a declaration which holds for the entire
current code block.
It means that the listed identifiers are part of the global
namespace.
• The Global statement cannot be reverted in a program run.
Try to avoid using global statement in Python Program.
• Better programming practice is to keep Global variables global,
and Local variables local.

REMEMBER:
SCOPE RULES apply to the identifiers or the name labels and NOT on the Values.
OUTPUT

NOTE: If a variable is declared global in a function, the function always refer to


the global variable and local variable cannot be created with the same name. Hence,
global variable ‘s value changes to 5 which is referenced inside function fun( ).

OUTPUT
OUTPUT
MUTABLE / IMMUTABLE
PROPERTIES OF DATA
OBJECTS
PASSING STRINGS, LISTS,
TUPLES, DICTIONARIES TO
FUNCTIONS
MUTABLE / IMMUTABLE properties of
PASSED DATA OBJECTS
IMPORTANT NOTES:
 Python’s variables are not storage containers, rather Python a
variables are like memory references which refer to the
memory address where the value is stored.
int 10
** Refer Fundamentals of Python PDF in the blog (knowpythonbytes) 1805363264
Here, Data type is integer, value is 10, variable name is a and memory address is 1805363264

As per the syllabus, you have learnt till now:


 Mutable Datatypes (whose values can be changed in place but, address of the
variable remains unchanged ): List,Dictionary,Sets
 Immutable Datatypes (whose values cannot be changed in place):
Numbers(integer,
IMPORTANT NOTES: float), Boolean, String, Tuple
 Depending upon the Mutablility / Immutability of a variable’s DATA TYPE; a
variable behaves differently.
 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, but 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.
PASSING IMMUTABLE TYPE VALUE TO THE FUNCTION

NOTE: Changes in immutable types are NOT


reflected in caller function at all.

OUTPUT
Before CALL in main

Inside fun()

Changed in fun()

Change NOT reflected

Here, in the above example, n is defined with value 20 in main which is of integer (Immutable) data type.
In the function call statement, n (actual parameter)is passed to p(formal parameter). The value of p
changes from 20 to (20*2=)40, inside the function fun(). When the control returns back to main, the
originally passed variable n remains unchanged. Changes do not get reflected to main.
PASSING MUTABLE TYPE VALUE TO THE FUNCTION: Adding, Deleting elements

NOTE: Changes, if any, in


mutable types are reflected
in caller function if its name
is not assigned a different
variable or data type.

OUTPUT
Before CALL in main
Element 11
Elements added removed

Changes reflected back in main

Here, in the above example, Mutable data type List, L is received by the function fun() and is referred by the List K. The
addition and deletion of elements are done to the List inside fun(). Changes get reflected to main in the List L.
PASSING MUTABLE TYPE VALUE TO THE FUNCTION:
Assigning parameter to a new variable/ name

NOTE: Changes, if any, in mutable types are NOT reflected in caller function if it
is assigned a different variable or data type because the addresses are different

OUTPUT Before CALL in main

Assigned List
K to New List

Changes NOT
reflected in main

Here, in the above example, Mutable data type List, L is received by the function fun() and is referred by the List K.
Changes in values do NOT get reflected to the main(caller) in the List L as it is assigned a different variable, New in fun( ).
Functions using libraries:
Mathematical and String functions.
From https://knowpythonbytes.blogspot.com/
• Refer to (Lets Lean Python Together) pdf file for
Mathematical Functions
• Refer to (Strings) pdf file for String Functions

Bibliograhy and References


• Google
• Wikipedia
• XII CS , By Sumita Arora, Dhanpat Rai Publication 2020
Edition
• XII IP , By Sumita Arora, Dhanpat Rai Publication 2020
Edition
Stay safe. Stay aware. Stay healthy. Stay alert.

You might also like