Module: A python module can be defined as a python program file which contains a python code including python
functions, class, or variables. In other words, we can say that our python code file saved with the extension (.py) is
treated as the module. We may have a runnable code inside the python module.
Importing Modules
Syntax: import module_name
Example: import math
print([Link](16)) # Output: 4.0
1. MATH MODULE: The math module provides mathematical functions.
Example: import math
print([Link](9)) # Square root
print([Link](2, 3)) # Power
print([Link](5)) # Factorial
print([Link]) # π value
print([Link]([Link]/2)) # Trigonometry
Functions:
[Link](x)- Square root of x. Ex: [Link](16) → 4.0
2. [Link](x, y)- x raised to the power y Ex: [Link](2, 3) → 8.0
3. [Link](x)- Factorial of x Ex: [Link](5) → 120
4. [Link]- Value of π (constant) Ex: [Link] → 3.141592...
5. math.e- Value of e (Euler's number) Ex: math.e → 2.71828...
2. RANDOM MODULE: The random module is used for random number generation.
Example: import random
print([Link](1, 10)) # Random integer
print([Link](['a', 'b'])) # Random choice from list
print([Link]()) # Random float between 0 and 1
Functions:
1. [Link]()- Random float between 0.0 and 1.0 Ex: [Link]() → 0.367...
2. [Link](a, b)- Random integer between a and b (inclusive) Ex: [Link](1, 6) → 3
3. [Link](a, b)- Random float between a and b Ex: [Link](1, 5) → 2.78
4. [Link](seq)- Random item from a sequence (list, tuple, etc.) Ex: [Link](['a', 'b']) → 'b'
Packages: The packages in python facilitate the developer with the application development environment by
providing a hierarchical directory structure where a package contains subpackages, modules, and sub-modules. The
packages are used to categorize the application.
How to Create Package in Python?
Creating packages in Python allows you to organize your code into reusable and manageable modules. Here‟s a brief
overview of how to create packages:
1. Create a Directory: Start by creating a directory (folder) for your package. This directory will serve as the root of
your package structure.
Source
1. [Link]
2. [Link]
3. [Link]
4. [Link]
2. Add Modules: Within the package directory, you can add Python files (modules) containing your code. Each
module should represent a distinct functionality or component of your package.
3. Init File: Include an init .py file in the package directory. This file can be empty or can contain an initialization code
for your package. It signals to Python that the directory should be treated as a package.
4. Subpackages: You can create sub-packages within your package by adding additional directories containing
modules, along with their own init .py files.
5. Importing: To use modules from your package, import them into your Python scripts using dot notation. For
example, if you have a module named [Link] inside a package named mypackage, you would import it like this:
from mypackage import module.
6. Distribution: If you want to distribute your package for others to use, you can create a [Link] file using
Python‟s setuptools library. This file defines metadata about your package and specifies how it should be installed.
File handling in Python is a powerful and versatile tool that can be used to perform a wide range of operations.
However, it is important to carefully consider the advantages and disadvantages of file handling when writing Python
programs, to ensure that the code is secure, reliable, and performs well.
Opening a File
Syntax: file = open("[Link]", "mode")
Reading From a File
f = open("[Link]", "r")
content = [Link]()
print(content)
[Link]()
Writing to a File
f = open("[Link]", "w")
[Link]("Hello Shivanshu!")
[Link]()
Appending to a File
f = open("[Link]", "a")
[Link]("\nNew Line added.")
[Link]()
Exception handling in Python allows programmers to manage and respond to unexpected events or errors during
program execution, without crashing the program. These errors are known as exceptions.
Why is Exception Handling Important?
- Prevents program from terminating unexpectedly.
- Provides meaningful error messages to users.
- Allows graceful recovery from unexpected errors.
Try-Except Block: The try-except block is used to catch and handle exceptions. Code that might raise an exception is
placed inside the try block. If an exception occurs, the except block is executed
Syntax:
try:
# risky code
except ExceptionType:
# handling code
Finally Block: A finally block contains code that will always execute, regardless of whether an exception was raised
or not. It is useful for clean-up activities.
Example:
try:
x = 10 / 2
except:
print("Something went wrong")
finally:
print("Execution completed.")
User-Defined Exceptions: Custom exceptions are created by defining a new class that inherits from the Exception
class.
Example:
class NegativeValueError(Exception):
pass
num = -1
if num < 0:
raise NegativeValueError("Negative values not allowed")
OOP(Object-Oriented Programming) is a programming paradigm based on the concept of "objects", which contain
data (attributes) and code (methods) that operates on the data.
Key Concepts of OOP:
1. Class & Oblect: A class is a blueprint for creating objects. An object is an instance of a class.
Example:
class Car:
def init (self, brand):
[Link] = brand
def start(self):
print(f"{[Link]} car started")
my_car = Car("Toyota")
my_car.start()
2. Encapsulation: Encapsulation in Python is a mechanism of bundling data (attributes) and methods that operate
on that data into a single unit (class). It restricts direct access to some of an object's components and prevents the
accidental modification of data. It promotes data hiding and abstraction, making the code more manageable and
secure.
Encapsulation is the process of wrapping data and the methods that operate on that data into a single unit.
Encapsulation is achieved through access modifiers:
Public: Accessible from anywhere.
Protected: Accessible within the class and its subclasses. Denoted by a single underscore prefix, e.g., _attribute.
Private: Accessible only within the class. Denoted by a double underscore prefix, e.g., __attribute.
Private members are prefixed with an underscore (_) or double underscore ( ).
Example:
class BankAccount:
def init (self):
self __balance = 0
def deposit(self, amount):
self. balance += amount
def show_balance(self):
print("Balance:", self. balance)
3. Inheritance: Inheritance in Python is a mechanism where a new class (child class or subclass) acquires attributes
and methods from an existing class (parent class or superclass). It facilitates code reuse and establishes a hierarchy
among classes.
Python supports single, multiple, and multilevel inheritance. In multiple inheritance, a class can inherit from multiple
parent classes.
Example:
class Animal:
def speak(self):
print("Animal speaks")
class Dog(Animal):
def bark(self):
print("Dog barks")
d = Dog()
[Link]()
[Link]()
4. Polymorphism: Polymorphism means many forms. It allows methods to do different things based on the object
calling them.
It refers to the ability of a single function, method, object, or operator to manifest in various forms. In essence,
itallows a single action to behave differently depending on the object it is applied to.
Example:
class Shape:
def area(self):
print("Calculating area")
class Circle(Shape):
def area(self):
print("Area of Circle")
s = Circle()
[Link]()
5. Abstraction: Abstraction in Python, a key principle of object-oriented programming, focuses on simplifying
complex systems by exposing only essential information to the user while hiding unnecessary implementation
details. This is achieved through abstract classes and methods.
Abstraction hides the internal details and shows only the functionality.
Overloading in Python refers to the ability to define multiple behaviors for a function, operator, or method based on
different input types or number of arguments. Python supports two main kinds of overloading:
1. Function Overloading: Python does not support traditional function overloading like some other languages (e.g.,
Java or C++). You cannot define multiple functions with the same name but different parameters. The last definition
will override the previous ones.
2. Operator Overloading: Python allows you to overload operators by defining special methods in a class. This
allows custom behavior for operators like +, -, *, etc.
Method overriding is a feature in object-oriented programming that allows a subclass to provide a specific
implementation of a method that is already defined in its parent (superclass).
In Python, method overriding happens when:
A child class defines a method with the same name as a method in the parent class.
The child class version of the method replaces the parent class version when called from an instance of the child
class.