Python Notes Unit-2
Python Notes Unit-2
Python Notes Unit-2
COURSE MATERIAL
For
UNIT-2
UNIT-II
TOPICS COVERED
1. Overview of Functions
2. Built-in functions
3. User defined functions
4. Types of user-defined functions
5. Calling and called functions
6. Function returning multiple values
7. Default arguments in Function
8. Variable length arguments in function (*args)
9. Keyword arguments (kwargs)
10. Variable -length keyword arguments (**kwargs)
11. Scope and lifetime of variables
a. Local and global variables
b. “global” keyword
12. Lambda function
13. Nested functions
14. Recursive function
15. Difference between recursion and iteration
16. Example recursive programs (gcd,factorial ,fibonacci series)
17. Overview of modules
18. Built -in modules
a. math
b. os
c. statistics
d. random
19. Creating and Importing User-Defined Modules
OVERVIEW OF FUNCTIONS
A function is a block of statements that performs a specific task.
The given problem is divided into pieces of sub problems and each sub problem is solved
independently. Finally the solution from each sub sub problem is collected and integrated
to the main problem.
This process is called the divide and conquer approach.
Functions can communicate with each other and also further decompose a problem into
other sub problems which perform a top-down approach(see figure-2).
Use of functions:
1. Functions simplify the process of program development by dividing a given
problem into subsections.Each subsection can be written and tested separately.
2. Coding and debugging individual functions is easier than coding and debugging
the entire big problem.
3. Code reusability is the main important usage of functions. Set of instructions can
be written in a function block and that functions can be called many times
whenever required.
4. Modularity is another important advantage of using functions. For example, if n
instructions to be executed in a program and those n instructions may appear
abruptly many times anywhere in the program, then instead of writing them again
for many times,those n instructions are written in a block of code, such that
whenever is needed program calls that function to execute those instructions.
Observe the figure-3.
5. Programmers can use the functions written by other programmers in their code
without rewriting them.
BUILT- IN FUNCTIONS
Python supports many built-in (predefined) functions. These functions are already
defined and come with the python software during its installation. Programmers can directly use
them by importing the required functions into their current programs.
Built-in functions reduce the burden on the programmer for rewriting the code again.
As python has many built-in functions, describing each function is out of scope. Few important
functions are listed and described here.
USER-DEFINED FUNCTIONS
Python allows the programmers to write and define their own functions other than built-
in functions. They are called user-defined functions or custom functions.
To create and use the user-defined functions, two properties must be used.
I. function definition: It provides the body of the function where the logic is written for
the function. To define a function, the keyword ‘del’ is used. Below is the syntax.
Notice that, in python ‘Indentation’ will be the begin and end of the function definition.No curly
braces must be used for representing blocks.
There are some rules to be followed for defining functions:
→ function name should not begin with a digit or special characters
→ function name should not be a keyword or reserved word
→ function name should not contain spaces
→ function body should follow an indentation with the same level for all
instructions.
→ a function may or may not take arguments as input. It depends on the logic of
the function. In above syntax,arg1,arg2,...argN are formal arguments to store inputs of function.
II. function call: Once function is defined and ready, by default it won't be executed like
regular statements. It must be called by another statement in the program to transfer the control
and execute the function definition. Function call uses the following syntax.
functionName(value1,value2,...valueN)
Here, value1,value2,...valueN are actual arguments or data to be given for function
definition to further compute and process the result.
Note: A function must be defined only once but once it is defined, it can be called many times in
the program (Reusability).
Example Output
#function call
functionName()
values and type of values should match in function call and function definition, otherwise leads
to error.
In the above figure, print() is a function which is calling another function test(). We say it as
function invocation. test() is the called function.
The control transfers from print() function to the definition of test() and executes the test
definition. The test() function produces the result 10 by returning it. ‘Return 10’ makes the
control return back to the print function and prints output as 10.
Consider the following figure:
In the above figure, the main program is invoking func1(), func1() is invoking func2() and
func2() is invoking func3(). func3() after its execution it returns its control back to func2().
func2() after its execution it returns its control to func1(). func1() after its execution, returns its
control to the main program and the main program completes its pending execution.
→ main program is a calling function to func1(). func1() will be a function to the main program.
→ Similarly, func1() is a calling function to func2() and func2() will be a called function to
func1().
→ func2() is a calling function to func3() and func3() will be a called function to func2().
Example Output
Syntax:
Example-1 Output
Example-2
Output
Syntax:
Example Output
In the above example, the test() function is called 3 times differently. In the first call, test() takes
3 values i.e 4, 5 and 6.These values will be replaced by x,y and z respectively. So, x=4,y=5 and
z=6.
In the second call, test() takes 2 values i.e 2 and 3. These values are replaced by only x and y. I.e
x=2 and y=3. As the third value is not given, z will have a default value. i.e z=3.
In the third call, test() takes no values. So default values will be used for x,y and z. ie. x=1,y=2
and z=3.
Note: The number of values must be less than or equal to the number of arguments declared in
function definition.
In python, if we do not know how many arguments to be passed into the function definition, then
we add a ‘*’ before the argument name in the function definition.
This way the function will receive a tuple of arguments, and can access the values accordingly.
Each value will be accessed from tuple argument through index.
Below is the syntax and example.
Syntax:
Example-1 Output
→ In example2, we have given variable arguments (*args) and also two normal arguments (x,y).
So the function call expects at least two values which will be assigned for x,y otherwise a
TypeError will be raised for missing values for x,y.
→ If more than two values are given , the first two values will be assigned to x,y and the rest of
the values will be assigned for ‘args’.
→ Always, the normal arguments should be assigned first and variable arguments should be
declared at last in function definition.
i.e def(x,y,*args): is valid but def(*args,x,y): and def(x,*args,y): are not valid.
Name of the key should match with any of the arguments in function definition.
Syntax:
Now you see that, irrespective of the order we follow, values of x,y and z are assigned to them
accordingly. During function call, we are specifying the interpreter which value should go to the
corresponding argument using the ‘key’. See the below figure.
Each argument value can be accessed using its corresponding key. We can do a function call
with many keyword arguments or a function call with no arguments at all.
Below is the syntax and example.
Syntax:
Example-1
(defining
variable-
keyword
arguments
and calling
function
with and
without
keyword
arguments)
Output
Example-2
(Accessing
each
keyword
argument
using for
loop)
Output
Depending on the above scenario, variables can be categorized into four types.
a. local variables
b. Global variables
c. Instance variables
d. Class variables
First two variables are discussed here and the rest of two variables are discussed in unit-3 (under
OOPs concepts).
a. Local variables:
Variables which are defined within a function are called local variables.
These variables can be accessed only within a function and can not be accessed outside
the function.
These variables are initialized only when a function is called.
These variables are valid till the end of the function execution. Once a function completes
its execution, local variables are deleted automatically and no longer valid in the
program.
If a function is called N times, then local variables are also created and deleted N times.
Local variables have a very short lifetime in the program.
Formal arguments are also treated as local variables.
Example: Output
b. Global variables:
Variables which are defined within a program are called global variables.
These variables can be accessed anywhere in the program, i.e inside a function and
outside a function.
Changing the value of a global variable by a function will reflect that change in other
functions and the entire program.
These variables are created and deleted only once when the program begins and exits.
These variables are valid till the end of the program execution.
Global variables have more lifetime than local variables.
Example Output
→ A local variable can be promoted to a global variable such that its scope and lifetime
will be increased. It can be accessed by all functions and anywhere in the program.
→ The local variable must be declared as ‘global’ for promoting the local variable to
global variable.
Example Output
Note-1: Both local variables and global variables cannot be used in a function at a time.
Note-2: If the names of both local variables and global variables are the same, then
priority will be given to local variables inside a function.
Write a python program to create,access, modify and delete the global variable.
program
Output
LAMBDA FUNCTION
● Lambda Function, also referred to as ‘Anonymous function’ is the same as a regular
python function but can be defined without a name.
● While normal functions are defined using the def keyword, anonymous functions are
defined using the ‘lambda’ keyword.
● Lambda functions are restricted to have only a single line of expression. They can take in
multiple arguments or no arguments as in regular functions.
● There is not much difference between regular function and lambda function except that
lambda functions should have only one expression for instant execution whereas regular
functions can have multiple expressions/instructions.
● Syntax and example of lambda function.
Syntax:
a= 5
square= 25
cube= 125
NESTED FUNCTIONS
A function defined inside another function is said to be a nested function(also referred as inner
function).
→ Inner function can access local variables of outer function but outer function cannot access
inner function local variables.
→ If Inner function has global variables , the outer function also can access it.
→ Inner function cannot be called directly. First main program invokes outer function which in
turn invokes inner function.
Syntax
Example Output
RECURSIVE FUNCTION
Recursion: The process of calling a function by itself until the final call doesn’t require the self
recursive call is called Recursion.
→ Functions which call themselves are called Recursive functions.
→ A recursive function requires two cases:
i) base condition: usually it is an if-else condition that allows or stops the further
recursive call.
ii) recursive case: the given problem is handed over to a recursive function which further
continues self recursive calls to obtain solution. Once a solution is obtained, it will be returned to
the main program by integrating the solutions from the parts of the recursive functions.
→ During recursion, depth of function calling increases.
→ Python allows a function to call itself upto a maximum limit of depth(1024 calls), after that
raises RuntimeError for further recursive call saying that maximum recursion depth limit
exceeded.
→ Recursion is mainly used to solve a given problem in a divide and conquer approach.
→ Divide and conquer: A big problem is divided into sub-problem , the sub-problem is again
divided into another sub-problem and this
process continues till no further division is
required. After dividing the problem, a solution
Example Output
RECURSION VS ITERATION
Recursion Iteration
Maintains a runtime stack memory to run all Uses runtime stack memory but not too much
recursive calls and store the data from the first like a recursive function. Deletes the data for
recursive call every iteration and loads data of current
iteration into stack.
Does not allow for further recursion if depth No maximum limit for iteration unless the
of recursion increases to maximum limit system signals by itself to stop further
iteration
Overload on the runtime stack to store all the No overload on runtime stack as it will clear
recursive data for the final solution which is the data for every iteration
not a very efficient way.
Difficult to find bugs if global variables are Easy than recursion to find bugs incase of
used global variables are used
Consumes more memory and time Less consumption of memory and time than
recursive functions
Program Output
Program Output
Program Output
OVERVIEW OF MODULES
What is a module? A module is a python program that contains the collection of functions,
global variables, classes and objects.
It is used to utilize the existing variables, functions, classes and objects in the current program
which are already defined in another python program.
Main idea of the module is to provide the Reusability of program codes like functions, variables,
classes and objects.
Also used to avoid the naming conflicts between the identifiers used in multiple programs.
Using a module, a current program can access many outside python programs and get their code
benefits.
Python supports many built-in modules. Lots of built-in modules already exist at the time of
python software installation.
Sometimes, there is a need to use external python libraries. Then they should be installed first
and then can be used in the program.
For example, modules like ‘numpy’,’pandas’
, ‘matplotlib’ modules could not exist by
default in python software.They must be
installed separately.
→ To use a module in the current program,
first the module should be imported into the
current program.
→ The keyword ‘import’ is used to import a
module into the program. Below is the syntax
for importing a module in different ways.
Syntax-1:
import moduleName
Import the specified module with the given
name
Example: import math
Syntax-2:
import module1,module2,...moduleN
Imports multiple modules
Example: import math,os,random
Syntax-3:
import moduleName as aliasName
Imports the specified module and can be accessed every time the module with the given alias
name.
Example: import random as rd
‘rd’ is the alias name which is used to access any data from a random module.
For example, rd.randint() can be called instead of random.randint()
Syntax-4:
from moduleName import *
Imports all variables,classes and functions from specified module. Equivalent to syntax-1.
Syntax-5:
from moduleName import object1,object2…,objectN
Imports only specified objects(variables,functions,classes) from the specified module.
Example:
from math import pi,sqrt,pow
Note: ‘import’ statement can be used anywhere in the program but it is recommended to import
modules at the beginning of the program.
BUILT-IN MODULES
Modules which are already defined and readily available to use in the program are called built-in
modules or pre-defined modules.
→ some built-in modules are already available during python installation but some modules are
to be installed separately.
→ four built-in modules are discussed below which already come with python installation.
a. math module :
This is a built-in module to perform mathematical tasks such as trigonometric
functions, operations on given numbers, representation functions, logarithmic functions,
etc.
→ To import math module, use the following syntax at the beginning of the program.
Syntax:
import math
It has many built-in functions and also built-in constants. Few of them are discussed
below.
Built-in constants:
Built-in functions:
b. os module:
It is a built-in module that provides variables and functions for interacting with the file
system of the operating system.
→ Used to create,read and delete directories in the os.
→ Also reads the information about users and running processes of the os.
To import os module we use the following syntax:
import os
os.walk(path) It displays the list of paths, directory names and file names in
the current directory given as a parameter.
Syntax:
for path,dname,fname in os.walk(os.getcwd()):
#print path,directories,files
Example:
c. Statistics module:
This is a built-in module used to calculate mathematical statistics of numeric data.
To import statistics module we use the following syntax:
import statistics
OR
import statistics as st
OR
from statistics import *
OR
from statistics import object1,object2…objectN
d. Random module:
It is a predefined module used to generate random numbers and perform manipulations
on those numbers.
Syntax:
import random
It has some built-in functions and few of them are discussed below.
Output:
Note-2: We can import only specific variables/functions from a module using below
syntax.
from moduleName import object1,object2,...objectN
Above syntax does not need a dot operator for accessing imported
variables/functions.They can be accessed directly.
Output:
Output:
module1.py
module2.py
Main.py
(importing
above two
modules)
output