Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
2 views

Python Module

This document provides an overview of Python modules, including how to create, use, and import them, as well as built-in modules like os, random, math, sys, and statistics. It explains various functions within these modules, such as creating directories, generating random numbers, performing mathematical operations, and handling command line arguments. Additionally, it covers Python packages, their structure, and how to import modules from them.

Uploaded by

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

Python Module

This document provides an overview of Python modules, including how to create, use, and import them, as well as built-in modules like os, random, math, sys, and statistics. It explains various functions within these modules, such as creating directories, generating random numbers, performing mathematical operations, and handling command line arguments. Additionally, it covers Python packages, their structure, and how to import modules from them.

Uploaded by

Gautham J K
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 41

Module -III

Python Modules
Python Module
• A file containing a set of functions you want to include in your
application.

Create and use a Module


• To create a module just save the code you want in a file with the file
extension .py
• use the module which is created by using the import statement
Python Module
• Import the module named mymodule, and call the greeting function
Variables in Module
Re-naming a Module
• can create an alias when you import a module, by using the as
keyword
Built-in Modules
• To display list of all available modules, use following command in
Python console:

>>> help('modules')
Built-in Modules – Frequently used
• os module
• random module
• math module
• time module
• sys module
• statistics module
OS Module
• This module has functions to perform many tasks of operating
system.
• mkdir()
• chdir()
• getcwd()
• rmdir()
• listdir()
OS Module
• mkdir()
create a new directory using mkdir() function from os module.

>>> import os
>>> os.mkdir(“Path:\\dir_name")

• A new directory corresponding to path in string argument in the


function will be created
OS Module
chdir()

• To change current working directory to use chdir() function.

>>> import os
>>> os.chdir(“<path>:\\temp")
OS Module
getcwd()
• This function in returns name off current working directory.
>>> os.getcwd()
'd:\\temp’
OS Module
• rmdir()
The rmdir() function in os module removes a specified directory
either with absolute or relative path. However it should not be the
current working directory and it should be empty.
OS Module
• listdir()
The os module has listdir() function which returns list of all files
in specified directory.
Random module
• Python’s standard library contains random module which defines
various functions for handling randomization
• random.random()
Returns a random float number between 0.0 to 1.0
The function doesn’t need any arguments

>>> import random


>>> random.random()
0.755173688207591
Random module
• random.randint()
Returns a random integer between the specified integers

>>> import random


>>> random.randint(1,100)
58
>>> random.randint(1,100)
91
Random module
• random.randrange()
Returns a random element from the range created by start, stop and step
arguments.
The start , stop and step parameters behave similar to range() function.

>>> random.randrange(1,10)
2
>>> random.randrange(1,10,2)
3
>>> random.randrange(0,101,10)
40
Random Module
• random.choice()
• Returns a randomly selected element from a sequence object such as
string, list or tuple.
• An empty sequence as argument raises IndexError

>>> import random


>>> random.choice('computer')
'o'
>>> random.choice([12,23,45,67,65,43])
65
>>> random.choice((12,23,45,67,65,43))
23
Random Module
• random.shuffle(): This functions randomly reorders elements in a list.

>>> numbers=[12,23,45,67,65,43]
>>> random.shuffle(numbers)
>>> numbers
[23, 12, 43, 65, 67, 45]
>>> random.shuffle(numbers)
>>> numbers
[23, 43, 65, 45, 12, 67]
Math module
• This module presents commonly required mathematical functions.
• trigonometric functions
• representation functions
• logarithmic functions
• angle conversion functions
Math Module
• radians(<number>): converts angle in degrees to radians
• degrees(<number>): converts angle in radians to degree.

• math.log(<number>): returns natural logarithm of given number. Natural


logarithm is calculated to the base e.
• math.log10(<number>): returns base-10 logarithm or standard logarithm
of given number.

• math.exp(<number>): returns a float number after raising e (math.e) to


given number. exp(x) is equivalent to e**x
• math.pow(<arg1>, <arg2>): This function receives two float arguments,
raises first to second and returns the result. pow(4,4) is equivalent to 4**4

• math.sqrt(<number>): This function computes square root of given


number
Representation functions
• The ceil() function approximates given number to smallest integer
greater than or equal to given floating point number.
• The floor() function returns a largest integer less than or equal to
given number

>>> math.ceil(4.5867)
5
>>> math.floor(4.5687)
4
sys module
• This module provides functions and variables used to manipulate
different parts of the Python runtime environment
sys module
sys.argv

• This return list of command line arguments passed to a Python script


• Item at 0th index of this list is always the name of the script.
• Rest of the arguments are stored at subsequent indices.
sys module
sys.argv
sys module
sys.exit
• This causes program to end and return to either Python
console or command prompt.
• It is used to safely exit from program in case of exception.
Sys Module
sys.maxsize

• It returns the largest integer a variable can take.

>>> import sys


>>> sys.maxsize
9223372036854775807
Statistics module
• mean() : calculate arithmetic mean of numbers in a list

>>> import statistics


>>> statistics.mean([2,5,6,9])
5.5
Statistics module

• median() : returns middle value of numeric data in a list.


• For odd items in list, it returns value at (n+1)/2 position.
• For even values, average of values at n/2 and (n/2)+1 positions is returned.

>>> import statistics


>>> statistics.median([1,2,3,8,9])
3
>>> statistics.median([1,2,3,7,8,9])
5.0
Statistics module
Time module
• time()

• This function returns current system time in ticks. The ticks is number
of seconds elapsed after epoch time i.e. 12.00 am, January 1, 1970.

• >>> time.time()
1544348359.1183174
Getting time string from seconds
• time.ctime()
Delaying Execution of programs
• Execution can be delayed using time.sleep() method.
• This method is used to halt the program execution for the time
specified in the arguments
Delaying Execution of programs
Creating a Time Delay in seconds
Creating a Time Delay in minutes
Python Packages

• Python has packages for directories and modules for files.


• Similar to file hierarchy in computers
• for example, keeping all the songs in the "music" directory

• As application program grows larger in size with a lot of modules


• we place similar modules in one package and different modules in different
packages.
• This makes a project (program) easy to manage and conceptually clear

• Similarly, as a directory can contain subdirectories and files, a Python


package can have sub-packages and modules.
Python Packages
• A directory must contain a file named __init__.py in order for Python
to consider it as a package.

• This file can be left empty but we generally place the initialization
code for that package in this file.
Python Packages - example
Importing module from a package
• can import modules from packages using the dot
(.) operator
Importing module from a package
• can import the module without the package prefix as follows:
Importing module from a package

You might also like