[Go to site: main page, start]

0% found this document useful (0 votes)
8 views135 pages

Functions in Python

The document discusses the importance of functions in programming, particularly in managing large programs by breaking them into smaller, manageable units. It covers the types of functions, advantages of using functions, and the concept of modularization, as well as details on user-defined functions, parameters, arguments, and the scope of variables. Additionally, it introduces recursion and its implementation conditions, emphasizing the significance of base conditions to prevent infinite loops.

Uploaded by

nareshram4804
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)
8 views135 pages

Functions in Python

The document discusses the importance of functions in programming, particularly in managing large programs by breaking them into smaller, manageable units. It covers the types of functions, advantages of using functions, and the concept of modularization, as well as details on user-defined functions, parameters, arguments, and the scope of variables. Additionally, it introduces recursion and its implementation conditions, emphasizing the significance of base conditions to prevent infinite loops.

Uploaded by

nareshram4804
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

WORKING WITH

FUNCTIONS
Introductio
n
◻ Large programs are often difficult to manage, thus
large programs are divided into smaller units known as
functions.
◻ It is simply a group of statements under any name i.e.
function name and can be invoked (call) from other
part of program.
◻ Take an example of School Management Software,
now this software will contain various tasks like
Registering student, Fee collection, Library book
issue, TC generation, Result Declaration etc. In this
case we have to create different functions for each task
to manage the software development.
-
Introductio
n
◻ Set of functions is stored in a file called MODULE.
And this approach is known as
MODULARIZATION, makes program easier to
understand, test and maintain.
◻ Commonly used modules that contain source code
for generic need are called LIBRARIES.
◻ Modules contains set of functions. Functions is of
mainly two types:
Built-in Functions
User-Defined Functions
S
Advantages of
Function
◻ PROGRAM HANDLING EASIER : only small part of
the program is dealt with at a time.
◻ REDUCED LoC: as with function the common set of
code is written only once and can be called from any
part of program, so it reduces Line of Code
◻ EASY UPDATING : if function is not used then set of
code is to be repeated everywhere it is required. Hence
if we want to change in any formula/expression then
we have to make changes to every place, if forgotten
then output will be not the desired output. With
function we have to make changes to only one
location.

S
User Defined
Functions
◻ A function is a set of statements that performs a
specific task; a common structuring elements that
allows you to use a piece of code repeatedly in
different part of program. Functions are also known as
sub-routine, methods, procedure or subprogram.
◻ Syntax to create USER DEFINED FUNCTION
def function_name([comma separated list of parameters]):
statements…
.
KEYWOR statements… FUNCTION
D DEFINITION
. S
Points to
remember…
◻ Keyword def marks the start of function header
◻ Function name must be unique and follows naming
rules same as for identifiers
◻ Function can take arguments. It is optional
◻ A colon(:) to mark the end of function header
◻ Function can contains one or more statement to
perform specific task
◻ An optional return statement to return a value from
the function.
◻ Function must be called/invoked to execute its code
S
User Defined function can
be….
1. Function with no arguments and no return
2. Function with arguments but no return
value
3. Function with arguments and return value
4. Function with no argument but return
value

Let us understand each of the function type


with example….
S
Function with no argument and no
return
◻ This type of function is also known as void
function
FUNCTION NO PARAMETER, HENCE
NAME VOID
Return keyword not used

FUNCTION CALLING, IT WILL INVOKE welcome() TO PERFORM


ITS ACTION
S
Function with parameters but no return
value
◻ Parameters are given in the parenthesis separated
by comma.
◻ Values are passed for the parameter at the time of
function calling.

S
Function with parameters but no return
value

S
Function with parameter and
return
◻ We can return values from function using
return keyword.
◻ The return value must be used at the calling
place by –
■ Either store it any variable
■ Use with print()
■ Use in any expression

S
Function with
return

S
Function with
return
NOTE: the return
statement ends a
function execution even if
it is in the middle of
function. Anything
written below return
statement will become
unreachable code.
def
max(x,y):
if x>y:
return
x
S
else:
print(“Iam not
return
Function not returning
value
◻ Function may or may not return a value. Non returning
function is also known as VOID function. It may or may not
contain return. If it contain return statement then it will be in
the form of:
[no value after return]
return

S
Parameters and Arguments in
Function
◻ Parameters are the value(s) provided in the parenthesis
when we write function header. These are the values
required by function to work
◻ If there are more than one parameter, it must be separated
by comma(,)
◻ An Argument is a value that is passed to the function when
it is called. In other words arguments are the value(s)
provided in function call/invoke statement
◻ Parameter is also known as FORMAL
ARGUMENTS/PARAMETERS ACTU
◻ Arguments is also known as
ARGUMENTS/PARAMETER AL
◻ Note: Function can alter only MUTABLE TYPE
values.
S
Example of Formal/Actual
Arguments

FORMAL
ARGUMENT

ACTUAL
ARGUMENT

S
Types of
Arguments
◻ There are 4 types of Actual Arguments allowed
in Python:
1. Positional arguments
2. Default arguments
3. Keyword arguments
4. Variable length arguments

S
Positional
arguments
◻ Are arguments passed to a function in
correct positional order

◻ Here x is passed to a and y is passed to b i.e. in the


order of their position
S
If the number of formal argument and actual differs
then Python will raise an error
S
Default
arguments
◻ Sometimes we can provide default values for our
positional arguments. In this case if we are not
passing any value then default values will be
considered.
◻ Default argument must not followed by non-default
arguments.
def VALID
interest(principal,rate,time=15):
def INVALID
interest(principal,rate=8.5,time=1
5): def S
Default
arguments

S
Default
arguments

S
Keyword(Named)
Arguments
◻ The default keyword gives flexibility to specify
default value for a parameter so that it can be
skipped in the function call, if needed. However,
still we cannot change the order of arguments in
function call i.e. you have to remember the order of
the arguments and pass the value accordingly.
◻ To get control and flexibility over the values sent
as arguments, python offers KEYWORD
ARGUMENTS.
◻ This allows to call function with arguments in any
order using name of the arguments.
S
Keyword(Named)
Argument

S
Rules for combining all three type of
arguments
◻ An argument list must first contain
positional arguments followed by
keyword arguments
◻ Keyword arguments should be taken from
the required arguments
◻ You cannot specify a value for an argument
more than once

S
Example of legal/illegal function
call
def
Average(n1,n2,n3=100):
return
FUNCTION CALL LEGAL/ REASON
(n1+n2+n3)/3 ILLEGA
L
Average(n1=20, n2=40,n3=80) LEGAL Non default values provided as
named arguments
Average(n3=10,n2=7,n1=100) LEGAL Keyword argument can be in
any order
Average(100,n2=10,n3=15) LEGAL Positional argument before
the keyword arguments
Average(n3=70,n1=90,100) ILLEGAL Keyword argument before the
positional arguments
Average(100,n1=23,n2=1) ILLEGAL Multiple values provided for n1
AveragVeIN(O20D I L LE G Undefined argument NUM2
O E F K AN
0 , n um 2 = 9 0 ,n A L
Returning Multiple
values
◻ Unlike other programming languages, python
lets you return more than one value from
function.
◻ The multiple return value must be either stored in
TUPLE or we can UNPACK the received value by
specifying the same number of variables on the
left of assignment of function call.
◻ Let us see an example of both :-

S
Multiple return value stored in
TUPLE

S
Multiple return value stored
by unpacking in multiple
variables

S
Compositio
n
◻ Refers to using an expression as a part of
large
expression, or a statement as a part large
of statement.
◻ Examples
Max((a+b),(c+a)) #
Prize(Card or Arithmetic
Cash) # Logical
name="Vikram“
print([Link]("m","nt").upper())
#function

S
Scope of Variables
◻ SCOPE means in which part(s) of the program,
a particular piece of code or data is accessible
or known.
◻ In Python there are broadly 2 kinds of Scopes:
Global Scope
Local Scope

S
Global Scope
◻ A name declared in top level segment( main ) of a
program is said to have global scope and can be
used in entire program.
◻ Variable defined outside all functions are global
variables.

S
Local
Scope
◻ A name declare in a function body is said to have
local scope i.e. it can be used only within this
function and the other block inside the function.
◻ The formal parameters are also having local scope.
◻ Let us understand with example….

S
Example – Local and Global
Scope

S
Example – Local and Global
Scope

„a‟ is not
accessible here
because it is
declared in
function area(), so
scope is local to
S area()
Example – Local and Global
Scope

Variable „ar‟ is accessible


in function showarea()
because it is having Global
Scope
S
This declaration “global count”
is necessary for using global
variables in function, other wise
an error “local variable
'count' referenced before
assignment” will appear
because local scope will create
variable “count” and it will be
found unassigned

S
Lifetime of
Variable
◻ Is the time for which a variable lives in memory.
For Global variables the lifetime is entire program
run
i.e. as long as program is executing. For Local
variables lifetime is their function‟s run i.e. as long
as function is executing.

S
Name Resolution (Scope
Resolution)
◻For every name used within program python follows name resolution
rules known as LEGB rule.
◻ (i) LOCAL : first check whether name is in local environment, if
yes Python uses its value otherwise moves to (ii)
◻ (ii) ENCLOSING ENVIRONMENT: if not in local, Python checks
whether name is in Enclosing Environment, if yes Python uses
its value otherwise moves to (iii)
◻ GLOBAL ENVIRONMENT: if not in above scope Python checks it
in Global environment, if yes Python uses it otherwise moves
to (iv)
◻ BUILT-IN ENVIRONMENT: if not in above scope, Python checks it
in built-in environment, if yes, Python uses its value otherwise
Python would report the error:
◻ name <variable> not defined
S
Predict the
output

Program with
variable “value”
in both LOCAL
and GLOBAL
SCOPE

S
Predict the
output

Program with
variable “value”
in both LOCAL
and GLOBAL
SCOPE

S
Predict the
output

Using GLOBAL
variable “value”
in local scope

S
Predict the
output
Using GLOBAL
variable “value”
in local scope

S
Predict the
output

Variable “value”
neither in local
nor global scope

S
Predict the
output

Variable “value”
neither in local
nor global scope

S
Predict the
output

Variable in Global
not in Local
(input in variable
at global scope)

S
Predict the
output

Variable in Global
not in Local
(input in variable
at global scope)

S
Mutability/Immutability of
Arguments/Parameters and
function call

S
Mutability/Immutability of
Arguments/Parameters and
function call

S
Mutability/Immutability of
Arguments/Parameters and
function call
◻ Python variables are not storage
containers, rather Python variables are like
memory references, they refer to memory address
where the value is stored, thus any change in
immutable type data will also change the
memory address. So any change to formal
argument will not reflect back to its
corresponding actual argument and in case of
mutable type, any change in mutable type will
not change the memory address of variable.

S
Mutability/Immutability of
Arguments/Parameters and
function call

Because List if Mutable type, hence any change in


formal argument myList will not change the memory
address, So changes done to myList will be reflected
back to List1.
However if we formal argument is assigned to some other variable
or data type then link will break and changes will not reflect back
to actual argument
For example (if inside function updateData() we assign
myList as: myList = 20OR myList = tempS
Understanding of main() function in
Python
◻ By default every program starts their execution
from main() function. In Python including a main()
function is not mandatory. It can structure our
Python
programs in a logical way that the
components of theprogram
importan puts most
t in
◻ function.
We one
can get the name of current module executing
by using built-in variable name (2 underscore
before and after of name)

S
Understanding of main() function in
Python

We can observe, by default the name of module will be main

Most non-python
programmers are having the
habit of writing main()
function where the important
and starter code of programs
are written. In Python we
can also create main()
and call it by checking
name to
main and then call
any
S function, in this case
Recursio
nIt is one of the
◻ most powerful tool in programming
language. It is a process where function calls itself
again and again.
◻ Recursion basically divides the big problem into small
problems up to the point where it can be solved easily,
for example if we have to calculate factorial of a 5, we
will divide factorial of 5 as 5*factorial(4), then
4*factorial(3), then 3*factorial(2), then 2*factorial(1)
and now factorial of 1 can be easily solved without any
calculation, now each pending function will be
executed in reverse order.

S
Condition for Implementing
Recursion
◻It must contain BASE CONDITION i.e. at which point recursion will
end otherwise it will become infinite.
◻ BASE CONDITION is specified using „if‟ to specify
the termination
condition
◻ Execution in Recursion is in reverse order using STACK. It first divide
the large problem into smaller units and then starts solving from
bottom to top.
◻ It takes more memory as compare to LOOP statement because with
every recursion call memory space is allocated for local variables.
◻ The computer may run out of memory if recursion becomes infinite or
termination condition not specified.
◻ It is less efficient in terms of speed and execution time
◻ Suitable for complex data structure problems like TREE, GRAPH etc
S
Example -
Recursion

S
Example -
Recursion

S
Flow of execution in a function call

Flow of execution refers to the order in which the


statements are executed during a program run.

Function Definition :
def greet():
Statements
Function call:
greet()
When fn. Call statement is encountered an execution frame
for the called function is created.
A function body is also a block. A block is executed in an
execution frame.
Execution Frame contains:
Name of the function.
Values passed to a function.
Variables created within a function.
Information about the next instruction to be executed.
Creating & calling a Function(user
defined)
A function is defined using the def keyword
in python.E.g. program is given below.

def my_own_function():
#Function block/
print("Hello from a function") definition/creation

#program start [Link] code


print("hello before calling a function")
my_own_function() #function [Link] function codes will be executed
print("hello after calling a function")

Save the above source code in python file and


execute it
Program execution begins with the first statement of
__main__ segment.
def statements are also read but ignored until called.

Function being called is called function.

Function calling another function is called caller function.


Example :

#to add 2 no.


def calcsum(x,y):
z=x+y
return z
n1=float(input("enter the first number"))
n2=float(input("enter the second number"))
sum=calcsum(n1,n2)
print("sum of 2 numbers= ",sum)
Actual flow of execution:

Execution begins at the first statement.


Comment lines are ignored.
Statements inside the function body are not executed until the
function is called.
A function can have another function(inner function) inside it.
Since inner fn. Is inside it will not be executed until the outer
function is called.
A function ends with return statement or last statement in the
function body, whichever occurs earlier.
USING PYTHON
LIBRARIES
COLLECTION OF
Modularization
of python
Frame program
-
work

Libr- Libr-
ary1 ary2

Pack Pack Pack Pack


- - - -
age1 age2 age3 age4

Framework=multiple library
mod-
ule1
mod-
ule2
Library=multiple packages
Package=multiple module
Module=multiple function/class
Using Python Libraries

Following terms must be clear while developing any python


project/program.
1. Module
2. Package
3. Library
4. Framework
1. Using -It is a file which contains python
Module
variables/clases etc. functions/global
It is just .py file which has python executable code /
[Link] example: Let’s create a file [Link]
def hello_message(user_name):
return “Hello " + name
Now we can import [Link] module either in python interpreter or
other py file.
import usermodule
print usermodule.hello_message(“India")
Using Python Libraries

How to import modules in Python?


Python module can be accessed in any of following way.
[Link] import statement
import math
print(“2 to the power 3 is ", [Link](2,3))
Just similar to math ,user defined module can be accessed using import
statement
[Link] with renaming
import math as mt
print(“2 to the power 3 is ", [Link](2,3))
[Link] from...import statement
from math import pow
print(“2 to the power 3 is ", pow(2,3))
[Link] all names
from math import *
print(“2 to the power 3 is ", pow(2,3))
Introduction

◻ As our program become larger and more complex the


need to organize our code becomes greater. We have
already learnt in Function chapter that large and
complex program should be divided into functions
that perform a specific task. As we write more and
more functions in a program, we should consider
organizing of functions by storing them in modules
◻ A module is simply a file that contains Python code.
When we break a program into modules, each modules
should contain functions that perform related tasks.
◻ Commonly used modules that contains source code for
generic needs are called Libraries.
Introduction

◻ When we speak about working with libraries in


Python, we are, in fact, working with modules that
are created inside Library or Packages. Thus a
Python program comprises three main components:
Library or Package
Module
Function/Sub-routine
Relationship between Module,
Package and Library in Python
◻ A Module is a file containing Python definitions
(docstrings) , functions, variables, classes and
statements
◻ Python package is simply a directory of Python
module(s)
◻ Library is a collection of various packages.
Conceptually there is no difference between
package and Python library. In Python a library is
used to loosely describe a collection of core or
main modules
Commonly used Python libraries
STANDARD LIBRARY
math module Provides mathematical functions
cmath module Provides function for complex numbers
random module For generating random numbers
Statistics module Functions for statistical operation
Urllib Provides URL handling functions so that you can access websites
from within your program.
NumPy library This library provides some advance math functionalities along
with tools to create and manipulate numeric arrays
SciPy library Another useful library that offers algorithmic and mathematical tools
for scientific calculation
Tkinter library Provides traditional user interface toolkit and helps you to create
user friendly GUI interface for different types of applications.
Malplotlib library Provides functions and tools to produce quality output in variety of
formats such as plot, charts, graph etc,
What is module?

◻ Act of partitioning a program into individual


components(modules) is called modularity. A
module is a separate unit in itself.
It reduces its complexity to some degree
It creates numbers of well-defined,
documented boundaries within program.
Its contents can be reused in other program,
without having to rewrite or recreate them.
Structure of Python module

◻ A python module is simply a normal python


file(.py) and contains functions, constants and
other elements.
◻ Python
docstring
module may contains following objects:
Triple quoted comments. Useful for documentation
purpose
Variables and For storing values
constants
Classes To create blueprint of any object
Objects Object is an instance of class. It represent class in real world
Statements Instruction
Functions Group of statements
Composition/Structure of python
module
MODUL
ES
VARIAB OTHER
LES PYTHON
MODUL
FUNCTION ES
S

VARIAB IMPOR
LES T
CLASS
ES
MEMBE OTHER
RS PYTHON
METHODS MODUL
ES
Importing Python modules

◻ To import entire module


■ import <module name>
■ Example: import math

◻ To import specific function/object from


module:
■ from <module_name> import <function_name>
■ Example: from math import sqrt
◻ import * : can be used to import all names
from module into current calling module
Accessing function/constant of imported
module
◻ To use function/constant/variable of imported
module we have to specify module name and function name
separated by dot(.). This format is known as dot notation.
■ <module_name>.<function_name>
■ Example: print([Link](25))
Example : import module_name
Example: from module import
function
◻ By this method only particular method will be
added to our current program. We need not to
qualify name of method with name of module.
Or example:
Here function
sqrt() is
directly written

This line will


not be executed
and gives an
error
Example: from module import *

◻ It is similar to importing the entire package as


“import package” but by this method qualifying
each function with module name is not required.

We can also import multiple elements of module as :


from math import sqrt, log10
Creating our own Module

◻ Create new python file(.py) and type the


following
code as: Execute the following code to import
and use your own module

Save this file are


“[Link]”
help() function

◻ Is used to getdetailed information about any


module like : name of module, functions inside
module, variables inside module and name of file
etc.
Namespace

◻ Is a space that holds a bunch of names. Consider an


example:
In a CCA competition of vidyalaya, there are students from
different classes having similar names, say there are three
POOJA GUPTA, one from class X, one from XI and one
from XII
As long as they are in their class there is no confusion,
since in X there is only one POOJA GUPTA, and same
with XI and XII
But problem arises when the students from X, XI, XII are
sitting together, now calling just POOJA GUPTA would
create confusion-which class‟s POOJA GUPTA. So one
need to qualify the name as class X‟s POOJA GUPTA, or
XI‟s or XII‟s and so on.
Namespace

◻ From the previous example, we can say that class X has its
own namespace where there no two names as POOJA
GUPTA; same holds for XI and XII.

◻ A namespace is a space that holds bunch of names.


◻ In Python terms, namespace can be thought of as a
named environment holding logical group of related
objects.

◻ For every python module(.py), Python creates a namespace


having its name similar to that of module‟s name. That is,
namespace of module AREA is also AREA.
Processing of import <module>

◻ The code of import module is interpreted and


executed
◻ Defined functions and variables in the module
are now available to program in new
namespace created by the name of module
◻ For example, if the imported module is area,
now you want to call the function area_circle(),
it would be called as area.area_circle()
Processing of from module import
object
◻ When we issue from module import object command:
■ The code of imported module is interpreted and executed
■ Only the asked function and variables from module are now available in
the current namespace i.e. no new namespace is created that’s why we
can call object of imported module without qualifying the module
name
■ For example:
from math import sqrt
print(sqrt(25))
■ However if the same function name is available in current
namespace then local function will hide the imported module’s
function
■ Same will be apply for from math import * method
Using Python‟s Built-in
Function
◻ Python‟s standard library is very extensive that
offers many built-in functions that we can use
without having to import any library.
◻ Using Python‟s Built-in functions
■ Function_name()
Mathematical and String functions

◻ oct(int) : return octal string for given number by prefixing


“0o”
◻ hex(int) : return octal string for given number by prefixing
“0x”
Mathematical and String functions

◻ int(number) : function convert the fractional


number to integer
◻ int(string) : convert the given string to integer
◻ round(number,[nDIGIT]) : return number rounded
to nDIGIT after decimal points. If nDIGIT is not
given, it returns nearest integer to its input.
◻ Examples: (next slide)
Mathematical and String functions
Other String function

◻ We have already used many string function in class


XI, here are few new functions
■ <string>.join() : if the string based iterator is a string then
the <string> is inserted after every character of the string.
■ If the string based iterator is a list or tuple of strings then, the
given string/character is joined after each member of the list of
tuple. BUT the tuple or list must have all members as string
otherwise Python will raise an error
◻ Examples (next slide)
Other String function
Other String function

◻ We have already used many string function in class


XI, here are few new functions
■ <string>.split() : allow to divide string in multiple parts
and store it as a LIST. If you do not provide delimeter then
by default string will be split using space otherwise using
given character.

■ <str>.replace() : allows you to replace any part of string


with another string.

■ Example (NEXT SLIDE)


Example (split() and replace())
Creating a Python Library

Package –
◻ collection of python modules under a common
namespace.
◻ Have different modules on a single directory with
some special files(such as __init__.py (content is
empty))
◻ If you don’t have __init__.py inside then it is called as
folder and not as package.
Structure of a package

Package:
Package vs Folder
Procedure for creating packages
◻ Decide about the basic structure of your package
◻ ie. Should have a clear idea about package name (folders, sub folders,
modules etc.,)
◻ Use underscore as separators and not any other spl. Characters.
◻ Create the directory structure having folders with names
of package and sub packages.
◻ Create __init__.py files in package and sub package
folders.
◻ Associate it with python installation. (refer next slide)
◻ After copying your package folder in your current python
installation now it becomes library so that any one can
import its modules and use its functions
Creating Package

◻ Step 1
■ Create a new folder which you want to act as package. The
name of folder will be the name of your package

IN THE C:\USERS\VIN
A new Folder “mypackage”
is created.
Note: you can create folder in
any desired location
Creating Package

◻ Step 2: Create modules (.py) and save it in


“mypackage” folder [Link]

[Link]
Creating Package

◻ Step 2: importing package and modules in python


program

Save this file by


“[Link]”
outside the package
folder

RUN THE PROGRAM


Creating Alias of Package/module

◻ Alias is the anothername for imported


package/module. It can be used to shorten the
package/module name

Save this file by


“[Link]”
outside the package
folder

RUN THE PROGRAM


PYTHON
MODULE
Group of functions, classes,
What is Python
Module
◻ A Module is a filecontaining Python
(docstring definitions
s)
, functions, variables, classes
statement
◻ s. and a program into individual
Act of partitioning
components(modules) is called modularity. A
module is a separate unit in itself.
It reduces its complexity to some degree
It creates numbers of well-defined, documented
boundaries within program.
Its contents can be reused in other program, without
having
Structure of Python
module
◻ A python module is simply a normal python
file(.py) and contains functions, constants and
other elements.
◻ Python
docstring
module may contains following
Triple quoted comments. Useful for documentation
objects: purpose
Variables For storing values
and
constants
Classes To create blueprint of any object
Objects Object is an instance of class. It represent class in real
world
Statements Instruction
Functions Group of statements
Composition/Structure of python
module
MODUL
ES
VARIABL OTHER
ES PYTHO
N
FUNCTION MODUL
S ES

VARIABL IMPO
ES
CLASSE RT
S
MEMBE OTHER
METHODS PYTHO
RS N
MODUL
ES
Importing Python
modules
◻ To import entire module
■ import <module name>
■ Example: import math

◻ To import specific function/object from


module:
■ from <module_name> import
<function_name>
■ Example: from math import sqrt
◻ import * : can be used to import all names
from module into current calling module
Accessing function/constant of imported
module
◻ To use function/constant/variable of imported
module we have to specify module name and
function name separated by dot(.). This format
is known as dot notation.
■ <module_name>.<function_name>
■ Example: print([Link](25))
◻ How ever if only particular function is imported
using from then module name before function
name is not required. We will se examples with
next slides.
Types of
Modules
◻ There are various in-built module in python,
we will discuss few of them
Math module
Random module
Statistical module
Math
module
◻ This module provides various function to
perform arithmetic operations.
◻ Example of functions in math modules are:
sqrt ceil floor pow
fabs sin cos tan
◻ Example of variables in math modules
are:
pi
e
Math module
functions
◻ sqrt(x) : this function returns the square
root of
number(x module name
is required
). before function
name here
◻ pow(x,y) : this function returns
the (x)y module name is
not required
before function
name here
◻ ceil : this function return the x rounded to
(x) next
intege
r.
Math module
functions
◻ floor(x) : thisfunction returns the x rounded to
previous integer.
◻ fabs(x) : thisfunction returns absolute value of
float x. absolute value means number without any sign

◻ sin (x) : it return sine of x (measured in


radian)
Math module
functions
◻ cos(x) : it return cosine of x (measured in
radian)

◻ tan(x) : it return tangent of x (measured in


radian)

◻ pi : return the constant value of pi


(22/7)

◻ e : return the constant value of


constant e
Using Random
Module
◻ Python has a module namely random that
provides random – number generators.
Random number means any number
generated within the given range.
◻ To generate random number in Python we
have to import random module
◻ 2 most common method to generate random
number in python are :
■ random() function
■ randint(a,b) function
random()
function
◻ It is floating point random number
generator between 0.0 to 1.0. here lower
limit is inclusive where as upper limit is
less than 1.0.
◻ 0<=N<1
◻ Examples:

Output is less
than 1
random()
function
◻ To generate random number between given
range of values using random(), the
following format should be used:
Lower_range + random() *
(upper_range-lower_range)
For example to generate number between 10 to
50:
■ 10 + random() * (40)
randint()
function
◻ Another way to generate random number is
randint() function, but it generate integer numbers.
◻ Both the given range values are inclusive i.e. if we
generate random number as :
randint(20,70)
■ In above example random number between 20 to 70
will be taken. (including 20 and 70 also)
E
X
A
M
P
L
E
O
U
T
P
U
T
Just a
Minute…
◻ Give the following python code, which is
repeated four times. What could be the
possible set of output(s) out of four sets (ddd
is any combination of digits)
import random
print(15 + [Link]()*5)
a) b) c) d)
[Link] [Link] [Link] [Link]
[Link] [Link] [Link] [Link]
[Link] [Link] [Link] [Link]
[Link] [Link] [Link] [Link]
Just a
Minute…
◻ What could be the minimum possible and
maximum possible numbers by following
code
import random
print([Link](3,10)
-3)
◻ In a school fest, three randomly chosen
students out of 100 students (having roll
number 1 -100) have to present the bouquet
to the guests. Help the school authorities
Just a
Minute…
Just a
Look at the following Python code and find the possible output(s) from
Minute…
the options (i) to (iv) following it. Also, write the maximum and the
minimum values that can be assigned to the variable PICKER.
Note:
- Assume all the required header files are already being included in the
code.
-The function randint() generates an integer between
1 to n import random
PICKER=1+[Link](0,2)
COLOR=[”BLUE”,”PINK”,”GREEN”,”RED”]
for I in range(1,PICKER+1):
for j in range(I+1):
print(COLOR[j],end=‘’)
print()
What are the possible outcome(s)
executed from the following code?
Also specify the maximum and
minimum values that can be
assigned to variable PICK
1) 2)
DELHIDELHI DELHI
MUMBAIMUMBAI DELHIMUMBAI
CHENNAICHENNAI DELHIMUMBAICHENN
KOLKATAKOLKAT AI
A
3) 4)
DELHI DELHI
MUMBAI DELHIMUMBAI
CHENNAI KOLKATAKOLKATAKOLKA
TA
KOKLATA
randrange()
function
◻ This function is also used to generate
random number within given range.
◻ Syntax
randrange(start,stop,step)
It will generate
random number
between 5 to 14

random output between 5 to 14, may


vary
randrange()
function
It will generate
random number
between 1 to 29
with stepping of 2
i.e. it will generate
number with gap
of 2 i.e.
1,3,5,7 and so on
Mathematics Game for
Kids
Mathematics Game for
Kids
Statistical
Module
◻ This provides functions for
module calculating statistics of numeric
mathematic (Real-valued)
◻ al
Wedata.
will deal with 3 basic function under this
module
Mean
Median
mode
Mea
n
◻ The mean is the average of all numbers
and is sometimes called the arithmetic
mean.

55, is the average of all numbers in


the list
Media
n
◻ The median is the middle number in a
group of numbers.
With odd number
of elements it will
simply return the
middle position
value

With even number


of elements, it will
return the average
of value at mid +
mid-1 i.e.
(50+60)/2 = 55.0
Mod
e
◻ The mode is the number that occurs most
often within a set of numbers i.e. most
common data in list.

Here, 10
occurs
most in the
list.

You might also like