Python Module
A Python module is a file containing Python definitions and statements. A module can
define functions, classes, and variables. Grouping related code into a module makes the code
easier to understand and use. It also makes the code logically organized.
Create a Python Module
Let’s create a simple module named [Link] in which we define one functions add
def add(x, y):
return (x+y)
Import module in Python
We can import the functions, and classes defined in a module to another module using
the import statement in some other Python source file.
Syntax of Python Import----import module
Example1
import addition
print([Link](10, 2))
Example2
import math
print( "The value of pi is", [Link] )
Python Import From Module
Python’s from statement lets you import specific attributes from a module without
importing the module as a whole.
from math import sqrt, factorial
print(sqrt(16))
print(factorial(6))
Import all Names
The * symbol used with the import statement is used to import all the names from a
module to a current namespace.
Syntax:
from module_name import *
from math import *
print(sqrt(16))
print(factorial(6))
Renaming the Python module
We can rename the module while importing it using the keyword.
Syntax: Import Module_name as Alias_name
Example import math as m
print([Link](16))
print([Link](6))
Python math Module
Python has a built-in module that you can use for mathematical tasks. The math module has a set
of methods and constants.
Math Methods
Method Description
[Link]() Returns the arc cosine of a number
[Link]() Returns the inverse hyperbolic cosine of a number
[Link]() Returns the arc sine of a number
[Link]() Returns the inverse hyperbolic sine of a number
[Link]() Returns the arc tangent of a number in radians
[Link]() Returns the inverse hyperbolic tangent of a number
[Link]() Rounds a number up to the nearest integer
[Link]() Returns the cosine of a number
[Link]() Returns the hyperbolic cosine of a number
[Link]() Converts an angle from radians to degrees
[Link]() Returns the error function of a number
[Link]() Returns the complementary error function of a
number
[Link]() Returns E raised to the power of x
[Link]() Returns the absolute value of a number
[Link]() Returns the factorial of a number
[Link]() Rounds a number down to the nearest integer
[Link]() Returns the remainder of x/y
[Link]() Returns the gamma function at x
[Link]() Returns the greatest common divisor of two integers
[Link]() Checks whether a number is finite or not
[Link]() Checks whether a number is infinite or not
[Link]() Checks whether a value is NaN (not a number) or not
[Link]() Rounds a square root number downwards to the
nearest integer
[Link]() Returns the natural logarithm of a number
math.log10() Returns the base-10 logarithm of x
math.log2() Returns the base-2 logarithm of x
[Link]() Returns the value of x to the power of y
[Link]() Returns the product of all the elements in an iterable
[Link]() Converts a degree value into radians
[Link]() Returns the sine of a number
[Link]() Returns the hyperbolic sine of a number
[Link]() Returns the square root of a number
[Link]() Returns the tangent of a number
[Link]() Returns the hyperbolic tangent of a number
[Link]() Returns the truncated integer parts of a number
Math Constants
Constant Description
math.e Returns Euler's number (2.7182...)
[Link] Returns a floating-point positive infinity
[Link] Returns a floating-point NaN (Not a Number) value
[Link] Returns PI (3.1415...)
[Link] Returns tau (6.2831...)
Python Time Module
As the name suggests Python time module allows to work with time in Python. It
allows functionality like getting the current time, pausing the Program from executing, etc. So
before starting with this module we need to import it.
Importing time module
The time module comes with Python’s standard utility module, so there is no need to
install it externally. We can simply import it using the import statement.
Syntax:- import time
epoch- The epoch is the point where the time starts and is platform-dependent.
[Link]() methods return the current time in seconds since epoch. It returns a floating-point
number.
[Link]() function returns a 24 character time string but takes seconds as argument and
computes time till mentioned seconds. If no argument is passed, time is calculated till the
present.
[Link]()- Execution can be delayed using [Link]() method. This method is used to halt
the program execution for the time specified in the arguments.
time.struct_time Class- Struct_time class helps to access local time . Its object contains the
following attributes –
Attribute
Index Name Values
0 tm_year 0000, …, 9999
1 tm_mon 1, 2, …, 11, 12
Attribute
Index Name Values
2 tm_mday 1, 2, …, 30, 31
3 tm_hour 0, 1, …, 22, 23
4 tm_min 0, 1, …, 58, 59
5 tm_sec 0, 1, …, 60, 61
6 tm_wday 0, 1, …, 6; Sunday is 6
7 tm_yday 1, 2, …, 365, 366
[Link]() method- localtime() method returns the struct_time object in local time.
[Link]() method- [Link]() is the inverse function of [Link]() which
converts the time expressed in seconds since the epoch to a time.struct_time object in local
time.
[Link]() method- [Link]() is used to convert a time expressed in seconds since the
epoch to a time.struct_time object in UTC
[Link]() method- [Link]() method converts the string representing time to the
struct_time object.
Random number in python
Generating random numbers in Python primarily involves the random module.
Generating a Random Integer within a Range:
To generate a random integer within a specified inclusive range, use
the randint() function from the random module:e.g.
import random
random_integer = [Link](1, 6)
print(random_integer)
Generating a Random Floating-Point Number:
To generate a random floating-point number between 0.0 (inclusive) and 1.0 (exclusive),
use the random() function:e.g.
import random
random_float = [Link]()
print(random_float)
Generating a Random Number from a Sequence:
To select a random element from a list, tuple, or string, use the choice() function:e.g.
import random
my_list = [1, 5, 8, 12, 20]
random_element = [Link](my_list)
print(random_element)
Namespaces
In Python, a namespace is a mapping from names to objects. It functions as a container
that stores identifiers (like variable names, function names, class names) and their corresponding
objects. Namespaces are crucial for organizing code, preventing naming conflicts, and managing
the scope and lifetime of variables.
Types of Namespaces:
1. Built-in Namespace: Contains Python's pre-defined functions and exceptions
(e.g., print(), len(), ValueError). This is always available.
2. Global Namespace: Created when a module is loaded or a script starts. It holds names
defined at the top level of a module.
3. Local Namespace: Created when a function is called. It contains names defined within
that function. This namespace exists only as long as the function is executing.
The lifetime of a namespace:
A lifetime of a namespace depends upon the scope of objects, if the scope of an object
ends, the lifetime of that namespace comes to an end. Hence, it is not possible to access the
inner namespace's objects from an outer namespace.
Example:
var = 5
def outer():
var = 6
def inner():
var = 7
print(var)
inner()
print(var)
outer()
print(var)
Scope and lookup rules in python
In Python, scope refers to the region of code where a variable or name is
accessible. Lookup rules dictate the order in which Python searches for a name when it's
referenced. These concepts are governed by the LEGB rule: Local, Enclosing, Global, and Built-
in.
Local (L) Scope:
This is the innermost scope.
Variables defined within a function are local to that function and are only accessible
within its body.
They are created when the function is called and destroyed when it finishes execution.
Enclosing (E) Scope:
This scope applies to nested functions.
If a variable is not found in the local scope of an inner function, Python searches the
enclosing scope of the outer function(s).
Global (G) Scope:
Variables defined at the top level of a module (outside any function or class) are global.
They are accessible throughout the entire module.
To modify a global variable inside a function, the global keyword must be used.
Built-in (B) Scope:
This is the outermost scope, containing Python's pre-defined names like print(), len(), etc.
These are always available without explicit import.
Lookup Rules (LEGB Order):
When Python encounters a name, it searches for it in the following order:
Local (L) scope: The current function's scope.
Enclosing (E) scope: The scope of any outer functions (if nested).
Global (G) scope: The module's top-level scope.
Built-in (B) scope: Python's built-in names.
If the name is not found in any of these scopes, a NameError is raised. This ordered search
ensures that names are resolved predictably and helps prevent naming conflicts.
Example:
var = 5
def outer():
var = 6
def inner():
var = 7
print(var)
inner()
print(var)
outer()
print(var)
Attributes and dot operator in python
In Python, attributes are values or characteristics associated with an object, while the dot
operator (.) is the mechanism used to access these attributes and methods of an object.
Attributes: Attributes can be categorized into:
Data Attributes (Instance Variables): These are variables that store data specific to an
individual object (instance) of a class. They are typically defined within the __init__ method
using self.attribute_name = value.
class Car:
def __init__(self, make, model):
[Link] = make # Data attribute
[Link] = model # Data attribute
my_car = Car("Toyota", "Camry")
Method Attributes: These are functions defined within a class that perform actions on or with
the object's data.
class Car:
def __init__(self, make, model):
[Link] = make
[Link] = model
def display_info(self): # Method attribute
print(f"Make: {[Link]}, Model: {[Link]}")
my_car = Car("Toyota", "Camry")
my_car.display_info() # Calling the method
Dot Operator (.): The dot operator is used to:
Access Data Attributes: Retrieve the value of a data attribute associated with an object.
my_car = Car("Toyota", "Camry")
print(my_car.make) # Accessing the 'make' attribute
Call Method Attributes: Execute a method associated with an object.
my_car = Car("Toyota", "Camry", 2023)
my_car.display_info() # Calling the 'display_info' method
Access Attributes of Modules and Packages: When importing modules or packages, the dot
operator is used to access their functions, classes, or other variables.
import math
print([Link]) # Accessing 'pi' attribute from the 'math' module