Table of Contents
What are modules?
Python has extensive libraries for supporting various functionalities like graphical user interface, database connectivity, mathematical calculations etc.
A file which consists of a collection of related functions is called as a module.
Python has many built-in modules like math, time, random etc.
Python also allows user to define its own modules according to the requirement such modules are called as user defined modules.
To use or call these modules in our script we use specific keywords like import and from.
In this post we will be studying math, time and random module in detail along with user defined modules.
Built-in modules in python
math module
The math module is the standard module in Python and is always available.
This module consist of all the mathematical functions and constants.
We can use this module with the help of import and from statements.
Syntax
>>> import math >>> import math as m >>> from math import * >>> from math import pi
Various function and constants in math module are:
Number-theoretic and representation functions
- ceil(x) : Return the ceiling of x as an int.This is the smallest integral value >= x
- copysign(x,y) : It returns x with the sign of y
- fabs(x) : It returns the absolute value of x
- factorial(x) : It returns factorial of x and raise a ValueError if x is negative or non-integral. floor(x) : Return the floor of x as an int.This is the largest integral value <= x
- fmod(x,y) : It returns remainder when x is divided by y
- fsum(iterable) : Return an accurate floating point sum of values in the iterable.
- ldexp(x, i) : It returns x * (2**i).
- modf(x) : It return the fractional and integer parts of x.
- trunc(x) : It returns the truncated integer value of x towards 0.
Power and logarithmic functions
- exp(x) : it returns e raised to the power of x i.e. e**2.
- expm1(x) : It returns e**x-1.
- log(x[, base]) : It returns the logarithm of x to the given base.If the base not specified, returns the natural logarithm (base e) of x
- log10(x) : It returns the base 10 logarithm of x. log2(x) : It returns the base 10 logarithm of x.
- pow(x, y) : It returns x**y (x to the power of y)
- sqrt(x) : It returns the square root of x.
Trigonometric functions
- acos(x) : It returns the arc cosine of x.
- asin(x) : It returns the arc sine of x.
- atan(x) : It returns the arc tangent of x.
- cos(x) : It returns the cosine of x (measured in radians). sin(x) : Return the sine of x (measured in radians).
- tan(x) : It returns the tangent of x (measured in radians).
- hypot(x, y) : Return the Euclidean distance, sqrt(x*x + y*y).
Angular functions
- degrees(x) : Convert angle x from radians to degrees.
- radians(x) : Convert angle x from degrees to radians.
Hyperbolic functions
- acosh(x) : It returns the inverse hyperbolic cosine of x.
- asinh(x) : It returns the inverse hyperbolic sine of x.
- atanh(x) : It returns the inverse hyperbolic tangent of x.
- cosh(x) : It returns the hyperbolic cosine of x.
- sinh(x) : It returns the hyperbolic sine of x.
- tanh(x) : It returns the hyperbolic tangent of x.
Special functions
- erf(x) : It returns error function at x.
- erfc(x) : It returns the complementary error function at x.
- gamma(x) : It returns Gamma function at x.
- lgamma(x) : It returns the natural logarithm of absolute value of Gamma function at x.
Constants
- pi : It represents a mathematical constant pi, pi = 3.141592653589793 .
- e : Standard mathematical constant e, e = 2.718281828459045.
Example
#math module print("Output of math module") print("------------------------------------------------------------") import math print("math.floor(1000.5)",math.floor(1000.5)) print("math.ceil(1000.5)",math.ceil(1000.5)) #fsum values=[0.9999999,1,2,3] r=math.fsum(values) print("math.fsum(values)",r) #truncate values print("math.trunc(123.45)",math.trunc(123.45)) #power method print("math.pow(2,3)",math.pow(2,3)) #sqrt method print("math.sqrt(4)",math.sqrt(4)) #use fabs method print("math.fabs(-123.5)",math.fabs(-123.5)) #use exp print("math.exp(2)",math.exp(2)) #use degrees print("math.degrees(.50)",math.degrees(.50)) #use radians print("math.radians(20)",math.radians(20))
OUTPUT

random module
The random module is used to deal with numbers in random manner in our program.
Syntax
>>> import random >>> import random as r >>> from random import * >>> from random import random
Various function and constants in random module are:
- seed() : It initializes the random number generator.
- getstate() : It returns the current internal state of the random number generator.
- setstate() : It restores the internal state of the random number generator.
- getrandbits() : It returns a number representing the random bits.
- randrange() : It returns a random number between the given range.
- randint() : It returns a random number between the given range.
- choice() : It returns a random element from the given sequence.
- choices() : It returns a list with a random selection from the given sequence.
- shuffle() : It takes a sequence and returns the sequence in a random order.
- sample() : It returns a given sample of a sequence.
- random() : It returns a random float number between 0 and 1
- uniform() : It returns a random float number between two given parameters
Example
#random module print("Output of random module") print("------------------------------------------------------------") import random #use random method print("random.random()",random.random()) #use randint method #generates random integer between a and b inclusive print("random.randint(1,5)",random.randint(1,5)) #use randrange(start,stop) method #generates random number in range(start,stop) print("random.randrange(10,15)",random.randrange(10,15)) #use seed method #initializes random number generator random.seed(100) print("random.random.seed(100)",random.random()) #use choice method #returns random element from non empty sequence print("random.choice([5,10,15])",random.choice([5,10,15])) print("random.choice('xyz')",random.choice('xyz')) #use shuffle method #shuffles the sequence list1=[1,2,3,5,10] random.shuffle(list1) print("shuffled list",list1) #use uniform method #returns random floating point number between a and b print("random.uniform(1,10)",random.uniform(1,10)) #use sample(population,k) method #returns k length list of unique elements chosen from the population sequence print("random.sample([1,2,3,4,5],2))",random.sample([1,2,3,4,5],2))
OUTPUT

time module
The time module is used to deal with the date and time related activity.
Syntax
>>> import time >>> import time as t >>> from time import * >>> from time import random
Various function and constants in random module are:
- time() — return current time in seconds since the Epoch as a float
- clock() — return CPU time since process start as a float
- sleep(seconds) — delay for a number of seconds given as a float
- gmtime([seconds]) — convert seconds since Epoch to UTC tuple (tm_year, tm_mon, tm_mday, tm_hour, tm_min, tm_sec, tm_wday, tm_yday, tm_isdst)
- localtime() — convert seconds since Epoch to local time tuple
- asctime([tuple]) — convert time tuple to string,e.g. ‘Sat Jun 06 16:26:11 1998’.When the time tuple is not present, current time as returned by localtime() is used.
- ctime() — convert time in seconds to string.This is equivalent to asctime(localtime(seconds)). When the time tuple is not present, current time as returned by localtime() is used.
- mktime() — convert local time tuple to seconds since Epoch
- strftime(format[, tuple]) — convert time tuple to string according to format specification.
- strptime(string,format) — parse string to time tuple according to format specification
- tzset() — change the local timezone
Commonly used format codes:
%Y Year with century as a decimal number.
%m Month as a decimal number [01,12].
%d Day of the month as a decimal number [01,31].
%H Hour (24-hour clock) as a decimal number [00,23].
%M Minute as a decimal number [00,59].
%S Second as a decimal number [00,61].
%z Time zone offset from UTC.
%a Locale’s abbreviated weekday name.
%A Locale’s full weekday name.
%b Locale’s abbreviated month name.
%B Locale’s full month name.
%c Locale’s appropriate date and time representation.
%I Hour (12-hour clock) as a decimal number [01,12].
%p Locale’s equivalent of either AM or PM.
The tuple of 9 integers giving local time
The tuple items are:
Index | Field | Values |
---|---|---|
0 | It represents a 4 digit year | eg: 2020 |
1 | It represents a month | 1 to 12 |
2 | It represents a day | 1 to 31 |
3 | It represents a hour | 0 to 23 |
4 | It represents a minute | 0 to 59 |
5 | It represents a second | 0 to 59 |
6 | It represents a day of week | 0 to 6 (0 is Monday) |
7 | It represents a day of year | 1 to 366 |
8 | It represents a daylight savings | flag (-1, 0 or 1) If the DST flag is 0, the time is given in the regular time zone. If it is 1, the time is given in the DST time zone. If it is -1, mktime() should guess based on the date and time. |
Example
#time module import time print("Output of time module") print("------------------------------------------------------------") #use time method print("The time output= ",time.time()) #use ctime method print("The ctime output= ",time.ctime()) #use sleep method for i in range(1,3): print("The sleep output= ",time.ctime()) time.sleep(i) #use gmttime method print("The gmttime output= ",time.gmtime()) print() #use localtime method print("The localtime output= ",time.localtime()) print() #use mktime method print("The mktime output= ",time.mktime(time.localtime())) print() #use strptime method print("The strptime output= ",time.strptime("14 Sep 20","%d %b %y")) print() #use strftime method print("The strftime output= ",time.strftime("%a, %d %b %Y %H:%M:%S",time.gmtime()))
OUTPUT

For other python basics related posts:
For other advanced python related posts: