Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 15

Modules and Functions

S.V.Jansi Rani
AP / CSE

S.V.JANSI RANI/AP/CSE/SSNCE 1
Modules
• A module is a file containing a collection of related functions.
• There are many Python modules that come with Python as part of
the standard library.
• The module object contains the functions and variables defined in
the module.
• To use the module import it.
• To access the functions, specify the name of the module and the
name of the function, separated by a dot. ( dot notation)

S.V.JANSI RANI/AP/CSE/SSNCE
Modules
import math
>>> print ( math . p i )
3.141592653589793
>>> print ( math . e )
2.718281828459045
>>> print ( math . s q r t ( 2 . 0 ) )
1.4142135623730951
>>> print ( math . s i n ( math . r a d i a n s ( 9 0 ) ) )
1.0

S.V.JANSI RANI/AP/CSE/SSNCE
Modules
import random
prob = random . random ( )
print ( prob )
diceThrow = random . r a n d ra n g e ( 1 ,10)
print ( diceThrow )

Output :
0.282475088414
1

S.V.JANSI RANI/AP/CSE/SSNCE
Modules
• Python has a number of functions built into it (80) that are always
available.

• https://docs.python.org/3/library/functions.html
• Math functions: abs(x), round(x, n)
• Type conversion functions: bool(x), float(x), int(x), long(x),
str(x)
• Input functions: input(x)
• Miscellaneous: len(x), help()

S.V.JANSI RANI/AP/CSE/SSNCE
S.V.JANSI RANI/AP/CSE/SSNCE
Why Functions
• It is worth to divide a program into functions.
• Creating a new function makes the program easier to read and debug.
• Functions can make a program smaller by eliminating repetitive code and
modifications are done in one place.
• Well-designed functions are often useful for many programs so it can be reused.

S.V.JANSI RANI/AP/CSE/SSNCE
Functions
A function is a named sequence of statements that performs a
computation.
Function is a reusable program code that performs a single, specific
well defined task.
Elements of functions
Function definition Function
call
Function deftnition: Consists of a function header followed by the
body of the function.
Function call : To use a function, call the function to perform the
defined task.

S.V.JANSI RANI/AP/CSE/SSNCE
Functions

S.V.JANSI RANI/AP/CSE/SSNCE
Functions

S.V.JANSI RANI/AP/CSE/SSNCE
S.V.JANSI RANI/AP/CSE/SSNCE
Function with return value

Output:

S.V.JANSI RANI/AP/CSE/SSNCE
Local and Global scope
def my_func():
x = 10
print("Value inside function:",x)
x = 20
my_func()

print("Value outside function:",x)

S.V.JANSI RANI/AP/CSE/SSNCE
To Do
Write a python program using function for the following
• find factors of a number
• Factorial of a number
• Sum of digits of a number

S.V.JANSI RANI/AP/CSE/SSNCE
THANK YOU

15
S.V.JANSI RANI/AP/CSE/SSNCE

You might also like