Best post on modules and built-in modules math,random & time-2

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.

>>> 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.
  • pi : It represents a mathematical constant pi, pi = 3.141592653589793 .
  • e : Standard mathematical constant e, e = 2.718281828459045.


#math module
print("Output of math module")
import math


#truncate values

#power method

#sqrt method

#use fabs method

#use exp

#use degrees

#use radians


Output of built-in modules-math
Output of math module

random module

The random module is used to deal with numbers in random manner in our program.

>>> 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


#random module
print("Output of random module")
import random
#use random method

#use randint method
#generates random integer between a and b inclusive

#use randrange(start,stop) method
#generates random number in range(start,stop)

#use seed method
#initializes random number generator

#use choice method
#returns random element from non empty sequence

#use shuffle method
#shuffles the sequence
print("shuffled list",list1)

#use uniform method
#returns random floating point number between a and b

#use sample(population,k) method
#returns k length list of unique elements chosen from the population sequence


Output of built-in modules-random
Output of random module

time module

The time module is used to deal with the date and time related activity.

>>> 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:

0It represents a 4 digit yeareg: 2020
1It represents a month1 to 12
2It represents a day1 to 31
3It represents a hour0 to 23
4It represents a minute0 to 59
5It represents a second0 to 59
6It represents a day of week0 to 6 (0 is Monday)
7It represents a day of year1 to 366
8It represents a daylight savingsflag (-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.


#time module
import time
print("Output of time module")
#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())
#use gmttime method
print("The gmttime output= ",time.gmtime())
#use localtime method
print("The localtime output= ",time.localtime())
#use mktime method
print("The mktime output= ",time.mktime(time.localtime()))
#use strptime method
print("The strptime output= ",time.strptime("14 Sep 20","%d %b %y"))
#use strftime method
print("The strftime output= ",time.strftime("%a, %d %b %Y %H:%M:%S",time.gmtime()))


Output of built-in modules-time
Output of time module

For other python basics related posts:

Best post on programming language and its types – 1
Python Programming (Basics) – History & Features
Python Programming (Basics)- Debugging & Types of errors
Python Programming (Basics) – Variables, Values, Types & Keywords.
Best post on built-in functions in python – 1
Python Programming (Basics) – Type Conversion
Python Programming (Basics) – Comments,Indentation,Built-in Number Data types and Expressions
Best post on IDLE & script mode in Python – 1
Python Programming (Basics)- Operators in Python
Best post on Order of Operations – Python
Simple and compound statements of python in easy way
Best post on conditional statements in python – Part 1
Best post on conditional statements in python – Part 2
Best post on looping in python (for loop)-Part 1
Best post on looping in python (while loop)-Part 2
Best post on nested loop in python(looping) -Part 3
Best post on infinite loop in python(looping) -Part 4
Best post on control statements(break,continue,pass)-1
Best post on Function definition & calling in python -1
Easy flow of function execution,parameters,arguments-2
Easy fruitful & void function,return values,stack diagrams-3
Best post on types of function arguments in python- 4
Best post on recursive function, scope of variable-5
Best post on import and from statement in python – 1
Best post on modules and built-in modules math,random & time-2
Best post on user defined modules in python-3
Best post on string datatype in python – 1
Best post immutable string,string operations python-2
Best post on string methods in python – 3
Best post on list datatype in python – 1
Best post on mutable list, list operations python – 2
Best post on List methods in python – 3
Best post on dictionary datatype in python – 1
Best post on dictionary methods and operations-2
Best post on tuple datatype in python – 1
Best post on tuple operations and immutable tuple- 2
Best post on tuple methods and built-in functions-3
17 -Python program to demonstrate Button in tkinter and its event in easy way
New posts coming soon.......

For other advanced python related posts:

File Systems and File Handling in Python
Types of file modes and attributes of file object in Python
How to read,write and append in a file in python?
Remaining file methods in Python
File Positions in Python
Directory in Python and its methods
Iterator and Iterables in Python
Exceptions in Python
Exception Handling in Python (Part I)
Exception Handling in Python (Part II)
Regular Expressions
Metacharacters or Regular Expression Patterns
Functions in 're' module(Part I)- Match vs Search
Functions in 're' module(Part II)-findall(), split(), sub()
Flags for regular expressions(Modifiers)
GUI programming in Python and Python GUI Library
What is Tkinter ?
Layout Manager (Geometry Manager) in Python
Events and Bindings in Python along with Widget configuration and styling
Fonts Names, Font Descriptors, System Fonts, Text formatting, Borders, Relief Styles in Python
Best post:Dimensions, Anchors, Bitmaps & Cursors in Python
Canvas widget of tkinter module – Python
Widgets in tkinter module – Python
Label, Text, Entry & Message Widget in Python
Button, Checkbutton & Radiobutton Widget in Python
Best post on Menu and Menubutton Widget of tkinter
Best post- Listbox and Scrollbar(Slider) Widget-Python
Best post on Frame Widget of tkinter in Python
Best post: message box widget and its methods
Best post- LabelFrame, Toplevel, PanedWindow widgets
Best post on Spinbox and Scale Widget in Python
Best post : Database connectivity in Python (Part 1)
Best post : Database Connectivity in Python (Part 2)
Best post on Create and Insert query : Python + MySQL
Best post on Select Query to Search & Read: Python + MySQL-4
Best post on Update query and Delete query : Python + MySQL-4
New posts coming soon.......

Leave a Comment