functions
functions
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>]
…..
…..
FLOW OF EXECUTION
OUTPUT Inside function
1561237
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.
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 2Passing fixed value FUNCTION CALL 5Function 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
In First Function call ,x and y takes 5 and 2 values in Function header 5-2 =3
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..
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)
Positional arguments
after keyword
arguments will result
into error !!!
RETURN
STATEMENTS
(returning single value
and multiple values)
RETURNING VALUE FROM FUNCTIONS
In Python,
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
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.
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 :
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
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
OUTPUT
Before CALL in main
Inside fun()
Changed in fun()
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
OUTPUT
Before CALL in main
Element 11
Elements added removed
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
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