MODULE 1: PROGRAMMING FUNDAMENTALS
1.1 Introduction to Programming
1.1.1 Meaning of Programming
Programming is the process of designing, writing, testing, and maintaining instructions
that enable a computer to perform a specific task. These instructions are written using a
programming language that the computer can understand and execute.
A program is a finite sequence of well-defined instructions to solve a problem.
1.1.2 Purpose of Programming
Programming is used to:
Solve real-world problems
Automate repetitive tasks
Process and analyze data
Develop software applications
Control hardware and systems
1.1.3 Programming Languages
Programming languages are broadly classified as:
Low-level languages (Machine language, Assembly language)
High-level languages (Python, Java, C, C++)
Python is a high-level, interpreted, and general-purpose programming language.
1.1.4 Program Development Steps
The steps involved in program development are:
1. Problem Definition
2. Algorithm Design
3. Flowchart Representation
4. Coding
5. Testing and Debugging
6. Documentation and Maintenance
1.2 Algorithms and Flowcharts
1.2.1 Algorithm
Definition
An algorithm is a step-by-step finite sequence of instructions used to solve a problem.
Characteristics of an Algorithm
An algorithm should have:
Input: Zero or more inputs
Output: At least one output
Definiteness: Clear and unambiguous steps
Finiteness: Terminates after finite steps
Effectiveness: Each step is basic and feasible
Example Algorithm
Algorithm to find the sum of two numbers
1. Start
2. Read two numbers A and B
3. Compute C = A + B
4. Display C
5. Stop
1.2.2 Flowchart
Definition
A flowchart is a graphical representation of an algorithm using standardized symbols to
show the flow of control.
Flowchart Symbols
Symbol Name Purpose
Oval Terminal Start / Stop
Parallelogram Input/Output Read / Print
Rectangle Process Computation
Diamond Decision Condition
Arrow Flow line Direction
Flowchart Example (Sum of Two Numbers)
Fig 1.1 Flow chart
1.3 Variables, Constants, and Data Types
1.3.1 Variables
Definition
A variable is a named memory location used to store data that can change during program
execution.
Rules for Naming Variables
Must start with a letter or underscore
Cannot start with a number
Cannot use keywords
Case-sensitive
Example
age = 20
name = "Gokul"
1.3.2 Constants
Definition
A constant is a value that does not change during program execution.
Example
PI = 3.14
MAX = 100
1.3.3 Data Types
Definition
A data type specifies the type of data that a variable can store.
Common Python Data Types
Data Type Description Example
int Integer 10
float Decimal 10.5
str String "Python"
bool Boolean True
Example Program
a = 10
b = 3.5
name = "Python"
status = True
1.4 Operators and Expressions
1.4.1 Operators
Definition
Operators are symbols used to perform operations on variables and values.
Types of Operators
1. Arithmetic Operators
+ - * / % // **
Example:
a = 10
b=3
print(a + b)
2. Relational Operators
<><= >= == !=
3. Logical Operators
and, or, not
4. Assignment Operators
= += -= *=
1.4.2 Expressions
An expression is a combination of variables, constants, and operators that evaluates to a
value.
Example:
result = (a + b) * 2
1.5 Input and Output Statements
1.5.1 Input Statement
Definition
Input statements are used to accept data from the user.
Python Input Function
num = int(input("Enter a number: "))
1.5.2 Output Statement
Definition
Output statements are used to display results.
Python Print Function
print("Number is:", num)
1.6 Control Structures
1.6.1 Conditional Statements
Definition
Conditional statements are used to make decisions based on conditions.
a) if Statement
if age >= 18:
print("Eligible to vote")
b) if-else Statement
if age >= 18:
print("Eligible")
else:
print("Not eligible")
c) elif Statement
if marks >= 90:
print("Grade A")
elif marks >= 75:
print("Grade B")
else:
print("Grade C")
1.6.2 Looping Statements
Definition
Loops are used to repeat a block of code multiple times.
a) for Loop
for i in range(1, 6):
print(i)
b) while Loop
i=1
while i<= 5:
print(i)
i += 1
1.7 Debugging Basics
1.7.1 Debugging
Definition
Debugging is the process of identifying and correcting errors (bugs) in a program.
Types of Errors
1. Syntax Errors
2. Runtime Errors
3. Logical Errors
Example
# Logical Error Example
a = 10
b=5
print(a - b) # Wrong logic if sum is required
Debugging Techniques
Reading error messages
Using print statements
Step-by-step execution
Testing with sample inputs
MODULE 2: CORE PYTHON
2.1 Introduction to Python
2.1.1 What is Python?
Python is a high-level, interpreted, object-oriented, and general-purpose programming
language developed by Guido van Rossum in the late 1980s and officially released in 1991.
Python emphasizes:
Code readability
Simplicity
Reduced development time
Python uses English-like syntax, making it easy to learn and use.
2.1.2 Features of Python
The important features of Python include:
1. Simple and Easy to Learn
Python’s syntax is straightforward and closely resembles natural language.
2. Interpreted Language
Python code is executed line by line, which makes debugging easier.
3. High-Level Language
Python abstracts hardware details such as memory management.
4. Object-Oriented
Supports classes, objects, inheritance, and polymorphism.
5. Portable
Python programs can run on multiple platforms without modification.
6. Extensive Standard Library
Includes modules for file handling, networking, database access, etc.
7. Open Source
Python is free and community-supported.
2.1.3 Applications of Python
Python is widely used in:
Web Development
Data Science and Machine Learning
Artificial Intelligence
Automation and Scripting
Game Development
Desktop Applications
Scientific Computing
2.2 Python Installation and Environment Setup
2.2.1 Python Distribution
Python is available as:
CPython (Standard Python)
Jython
IronPython
PyPy
CPython is the most commonly used distribution.
2.2.2 Installing Python
Steps for Installation
1. Download Python from the official website
2. Run the installer
3. Select Add Python to PATH
4. Complete installation
2.2.3 Python Interpreter
Python provides an interactive interpreter, where commands are executed immediately.
Example:
>>>print("Hello Python")
Hello Python
2.2.4 Integrated Development Environments (IDEs)
Common Python IDEs:
IDLE
PyCharm
VS Code
Spyder
Jupyter Notebook
An IDE provides:
Code editor
Debugger
Syntax highlighting
Auto-completion
2.2.5 Virtual Environment
A virtual environment is an isolated workspace used to manage project-specific
dependencies.
Benefits:
Avoids package conflicts
Maintains clean system Python installation
2.3 Python Syntax and Indentation
2.3.1 Python Syntax
Python syntax refers to the rules that define how Python programs are written and
interpreted.
Key characteristics:
No semicolons
No braces { }
Uses indentation to define code blocks
2.3.2 Indentation in Python
Indentation refers to the spaces at the beginning of a line.
In Python:
Indentation is mandatory
Incorrect indentation leads to errors
Example
if True:
print("Correct Indentation")
Incorrect:
if True:
print("Error")
2.3.3 Importance of Indentation
Improves code readability
Eliminates ambiguity
Enforces structured programming
2.4 Keywords and Identifiers
2.4.1 Keywords
Definition
Keywords are reserved words in Python that have predefined meanings and cannot be used
as variable names.
Examples of Python Keywords
if, else, elif, while, for, break, continue, True, False, None, class, def, return, import
Example
if = 10 # Invalid
2.4.2 Identifiers
Definition
Identifiers are names used to identify variables, functions, classes, and objects.
Rules for Identifiers
Must begin with a letter or underscore
Can contain letters, digits, and underscores
Cannot be a keyword
Case-sensitive
Valid Identifiers
total
_sum
studentName
Invalid Identifiers
2value
total-price
class
2.5 Python Comments
2.5.1 Purpose of Comments
Comments are used to:
Explain code
Improve readability
Assist debugging
Document logic
Comments are ignored by the Python interpreter.
2.5.2 Single-Line Comments
Single-line comments use the # symbol.
# This is a comment
x = 10
2.5.3 Multi-Line Comments
Python does not have a specific multi-line comment syntax, but triple quotes are commonly
used.
"""
This is a
multi-line comment
"""
2.6 Python Data Types
2.6.1 Concept of Data Types
A data type defines:
Type of data stored
Size of memory allocated
Operations that can be performed
Python is a dynamically typed language, meaning data type is determined at runtime.
2.6.2 Numeric Data Types
a) int (Integer)
Definition
int represents whole numbers without decimal points.
Example
a = 100
b = -25
Characteristics
Unlimited precision
Can be positive or negative
b) float
Definition
float represents real numbers with decimal points.
Example
pi = 3.14159
rate = 12.5
Scientific Notation
num = 2.5e3
c) complex
Definition
A complex number consists of a real part and an imaginary part.
Example
c = 3 + 4j
Accessing Parts
print([Link])
print([Link])
2.6.3 Boolean Data Type
Definition
The bool data type represents True or False values.
Example
is_active = True
is_logged_in = False
Usage
Used in:
Decision making
Conditional statements
Loop conditions
2.6.4 String Data Type
Definition
A string is a sequence of characters enclosed in quotes.
Examples
name = "Python"
language = 'Programming'
String Operations
Concatenation
Repetition
Indexing
Slicing
Example
msg = "Hello"
print(msg[0])
print(msg[1:4])
2.7 Type Conversion
2.7.1 Type Conversion Overview
Type conversion refers to the process of converting one data type into another.
Python supports:
1. Implicit Type Conversion
2. Explicit Type Conversion
2.7.2 Implicit Type Conversion
Definition
Automatically performed by Python without programmer intervention.
Example
a = 10
b = 2.5
c=a+b
print(c)
Result: float
2.7.3 Explicit Type Conversion (Type Casting)
Definition
Manually converting data types using built-in functions.
Common Conversion Functions
Function Converts To
int() Integer
float() Float
str() String
bool() Boolean
complex() Complex
Examples
x = "10"
y = int(x)
a=5
b = str(a)
Conversion Errors
int("abc") #ValueError
Importance of Type Conversion
Ensures correct calculations
Avoids runtime errors
Enables user input processing
MODULE 3: PYTHON DATA STRUCTURES
3.1 Introduction to Data Structures
3.1.1 Meaning of Data Structures
A data structure is a systematic way of organizing, storing, and managing data in
memory so that it can be accessed and modified efficiently.
In Python, data structures allow programmers to:
Store large amounts of data
Perform operations efficiently
Represent real-world data logically
3.1.2 Built-in Data Structures in Python
Python provides several built-in data structures:
Strings
Lists
Tuples
Sets
Dictionaries
These data structures differ in terms of:
Mutability
Ordering
Uniqueness of elements
Access methods
3.2 Strings and String Operations
3.2.1 String Definition
A string is a sequence of characters enclosed within:
Single quotes ' '
Double quotes " "
Triple quotes ''' ''' or """ """
Strings are immutable, meaning their contents cannot be changed after creation.
Examples
name = "Python"
course = 'Full Stack'
message = """Welcome to Python"""
3.2.2 Accessing Strings
Indexing
Each character in a string is assigned an index starting from 0.
s = "Python"
print(s[0]) # P
print(s[-1]) # n
Slicing
Slicing extracts a portion of a string.
print(s[0:4]) # Pyth
print(s[2:]) # thon
print(s[:3]) # Pyt
3.2.3 String Operations
a) Concatenation
a = "Hello"
b = "World"
print(a + b)
b) Repetition
print("Hi " * 3)
c) Membership Operators
print("Py" in "Python")
print("Java" not in "Python")
d) Comparison
print("abc" == "ABC")
3.2.4 String Methods
Method Description
lower() Converts to lowercase
upper() Converts to uppercase
strip() Removes spaces
replace() Replaces substring
split() Splits string
Example
text = " Python Programming "
print([Link]())
print([Link]())
3.3 Lists
3.3.1 Definition of List
A list is an ordered collection of heterogeneous elements, enclosed in square brackets [ ].
Lists are mutable, meaning elements can be changed.
Example
numbers = [10, 20, 30]
data = [1, "Python", 3.5, True]
3.3.2 List Indexing
lst = [10, 20, 30, 40]
print(lst[1])
print(lst[-1])
3.3.3 List Slicing
print(lst[1:3])
print(lst[:2])
print(lst[2:])
3.3.4 List Methods
Method Purpose
append( Adds element at end
)
insert() Adds at specific index
remove() Removes element
pop() Removes by index
sort() Sorts list
reverse() Reverses list
Example
lst = [3, 1, 4]
[Link](2)
[Link]()
print(lst)
3.3.5 Traversing a List
for item in lst:
print(item)
3.4 Tuples
3.4.1 Definition of Tuple
A tuple is an ordered collection of elements enclosed within parentheses ( ).
Tuples are immutable.
Example
t = (10, 20, 30)
3.4.2 Tuple Characteristics
Faster than lists
Immutable
Allows duplicate values
Can store different data types
3.4.3 Tuple Operations
Indexing and Slicing
print(t[0])
print(t[1:3])
Tuple Packing and Unpacking
a = (1, 2, 3)
x, y, z = a
3.5 Sets
3.5.1 Definition of Set
A set is an unordered collection of unique elements, enclosed within { }.
Example
s = {1, 2, 3, 4}
3.5.2 Characteristics of Sets
No duplicate values
Unordered
Mutable
Cannot access elements using index
3.5.3 Set Operations
a) Union
a = {1, 2}
b = {2, 3}
print(a | b)
b) Intersection
print(a & b)
c) Difference
print(a - b)
d) Symmetric Difference
print(a ^ b)
3.6 Dictionaries
3.6.1 Definition of Dictionary
A dictionary is a collection of key–value pairs, enclosed within { }.
Example
student = {
"name": "Gokul",
"age": 20,
"course": "Python"
}
3.6.2 Accessing Dictionary Elements
print(student["name"])
3.6.3 Dictionary Methods
Method Description
keys() Returns keys
values() Returns values
items() Returns key-value pairs
get() Safe access
pop() Removes item
Example
print([Link]())
print([Link]())
3.6.4 Updating Dictionary
student["age"] = 21
3.7 Mutable vs Immutable Objects
3.7.1 Mutable Objects
Mutable objects can be modified after creation.
Examples:
List
Dictionary
Set
Example
lst = [1, 2, 3]
lst[0] = 10
3.7.2 Immutable Objects
Immutable objects cannot be changed after creation.
Examples:
int
float
string
tuple
Example
s = "Python"
# s[0] = 'J' → Error
3.7.3 Comparison Table
Feature Mutable Immutable
Changeable Yes No
Memory Efficiency Lower Higher
Examples list, dict int, str
MODULE 3: PYTHON DATA STRUCTURES
3.1 Introduction to Python Data Structures
3.1.1 Meaning of Data Structures
A data structure is a method of organizing, storing, and managing data in memory so that it
can be accessed and modified efficiently. Proper data structures improve program
performance and make code more readable and maintainable.
Python provides several built-in data structures that allow programmers to handle large
volumes of data with ease.
3.1.2 Classification of Data Structures
Python data structures can be broadly classified as:
Sequence Data Types – Strings, Lists, Tuples
Non-Sequence Data Types – Sets, Dictionaries
3.2 Strings and String Operations
3.2.1 Definition of String
A string is a sequence of characters enclosed within single quotes (' '), double quotes (" "), or
triple quotes (''' ''' or """ """).
Strings are immutable, meaning once created, their contents cannot be modified.
Example
name = "Python"
course = 'Data Structures'
message = """Welcome to Python Programming"""
3.2.2 String Indexing
Each character in a string has a unique position called an index.
Positive indexing starts from 0
Negative indexing starts from -1
s = "Python"
print(s[0]) #P
print(s[-1]) # n
3.2.3 String Slicing
Slicing is used to extract a portion of a string using the format:
string[start : end]
print(s[0:4]) # Pyth
print(s[2:]) # thon
print(s[:3]) # Pyt
3.2.4 String Operations
a) Concatenation
a = "Hello"
b = "World"
print(a + " " + b)
b) Repetition
print("Python " * 3)
c) Membership Operators
print("Py" in "Python")
print("Java" not in "Python")
d) Comparison Operators
print("apple" == "Apple")
3.2.5 String Methods
Method Description
lower() Converts string to lowercase
upper() Converts string to uppercase
strip() Removes whitespace
replace() Replaces a substring
split() Splits string into a list
Example
text = " Python Programming "
print([Link]())
print([Link]())
3.3 Lists
3.3.1 Definition of List
A list is an ordered collection of elements enclosed in square brackets [ ].
Lists are mutable, meaning elements can be changed after creation.
Example
numbers = [10, 20, 30, 40]
data = [1, "Python", 3.14, True]
3.3.2 List Indexing
lst = [5, 10, 15, 20]
print(lst[1])
print(lst[-1])
3.3.3 List Slicing
print(lst[1:3])
print(lst[:2])
print(lst[2:])
3.3.4 List Methods
Method Purpose
append() Adds element at the end
insert() Adds element at a specific index
remove() Removes specified element
pop() Removes element using index
sort() Sorts elements
reverse() Reverses list
Example
lst = [3, 1, 4]
[Link](2)
[Link]()
print(lst)
3.4 Tuples
3.4.1 Definition of Tuple
A tuple is an ordered collection of elements enclosed in parentheses ( ).
Tuples are immutable, meaning elements cannot be modified.
Example
t = (10, 20, 30)
3.4.2 Tuple Characteristics
Immutable
Ordered
Allows duplicate values
Faster than lists
3.4.3 Tuple Operations
Indexing and Slicing
print(t[0])
print(t[1:3])
Tuple Packing and Unpacking
a = (1, 2, 3)
x, y, z = a
3.5 Sets
3.5.1 Definition of Set
A set is an unordered collection of unique elements, enclosed within curly braces { }.
Example
s = {1, 2, 3, 4}
3.5.2 Characteristics of Sets
No duplicate elements
Unordered
Mutable
Indexing not supported
3.5.3 Set Operations
Union
a = {1, 2}
b = {2, 3}
print(a | b)
Intersection
print(a & b)
Difference
print(a - b)
Symmetric Difference
print(a ^ b)
3.6 Dictionaries
3.6.1 Definition of Dictionary
A dictionary is a collection of key–value pairs, where each key is unique.
Dictionaries are enclosed within curly braces { }.
Example
student = {
"name": "Gokul",
"age": 21,
"course": "Python"
3.6.2 Accessing Dictionary Elements
print(student["name"])
3.6.3 Dictionary Methods
Method Description
keys() Returns all keys
values() Returns all values
items() Returns key-value pairs
get() Safe key access
pop() Removes key-value pair
3.6.4 Updating Dictionary
student["age"] = 22
3.7 Mutable vs Immutable Objects
3.7.1 Mutable Objects
Mutable objects can be modified after creation.
Examples:
List
Dictionary
Set
lst = [1, 2, 3]
lst[0] = 10
3.7.2 Immutable Objects
Immutable objects cannot be changed after creation.
Examples:
int
float
string
tuple
s = "Python"
# s[0] = 'J' # Error
3.7.3 Comparison Table
Feature Mutable Immutable
Modification Allowed Not Allowed
Memory Usage Higher Lower
Examples list, dict, set int, str, tuple
MODULE 4: CONTROL FLOW AND FUNCTIONS
1. Decision Making Statements
Definition:
Decision-making statements are used to execute different blocks of code based on a
condition. Python evaluates conditions as True or False.
Types of Decision-Making Statements
1. if
2. if–else
3. if–elif–else
4. Nested if
1.1 if Statement
Syntax:
if condition:
statement
Example:
x = 10
if x > 5:
print("x is greater than 5")
1.2 if–else Statement
Syntax:
if condition:
statement1
else:
statement2
Example:
num = 7
if num % 2 == 0:
print("Even number")
else:
print("Odd number")
1.3 if–elif–else Statement
Syntax:
if condition1:
statement1
elif condition2:
statement2
else:
statement3
Example:
marks = 75
if marks >= 90:
print("Grade A")
elif marks >= 60:
print("Grade B")
else:
print("Grade C")
1.4 Nested if Statement
Definition:
An if statement inside another if statement.
Example:
x = 10
y=5
if x > 0:
if y > 0:
print("Both are positive")
2. Loop Control Statements
Definition:
Loop control statements alter the normal flow of loops.
Types:
break
continue
pass
2.1 break Statement
Definition:
Terminates the loop immediately when encountered.
Example:
for i in range(1, 6):
if i == 4:
break
print(i)
Output:
1
2
3
2.2 continue Statement
Definition:
Skips the current iteration and moves to the next iteration.
Example:
for i in range(1, 6):
if i == 3:
continue
print(i)
Output:
1
2
4
5
2.3 pass Statement
Definition:
Acts as a placeholder where a statement is syntactically required but no action is needed.
Example:
for i in range(5):
if i == 2:
pass
print(i)
3. Functions
Definition:
A function is a reusable block of code that performs a specific task.
Advantages of Functions:
Code reusability
Modular programming
Easy debugging and maintenance
3.1 Built-in Functions
Definition:
Functions provided by Python by default.
Examples:
print()
len()
type()
sum()
max()
min()
numbers = [1, 2, 3]
print(len(numbers))
3.2 User-defined Functions
Definition:
Functions created by the user using the def keyword.
Syntax:
def function_name(parameters):
statements
return value
Example:
def greet():
print("Hello, Python")
greet()
3.3 Parameters and Return Values
Parameters
Variables used to receive values passed to a function.
Example:
def add(a, b):
print(a + b)
add(3, 4)
Return Values
Used to send a result back to the calling function.
Example:
def multiply(x, y):
return x * y
result = multiply(4, 5)
print(result)
4. Lambda Functions
Definition:
A lambda function is an anonymous, single-expression function.
Syntax:
lambda arguments: expression
Example:
square = lambda x: x * x
print(square(5))
Key Characteristics:
No function name
Used for short operations
Single expression only
5. Recursion
Definition:
Recursion is a technique where a function calls itself to solve a problem.
Components of Recursion:
1. Base condition
2. Recursive call
Example: Factorial of a Number
def factorial(n):
if n == 1:
return 1
else:
return n * factorial(n - 1)
print(factorial(5))
Output:
120
Advantages of Recursion
Simplifies complex problems
Reduces code length
Disadvantages of Recursion
Higher memory usage
Slower execution if not optimized
MODULE 5: OBJECT-ORIENTED PROGRAMMING (OOP)
Introduction to Object-Oriented Programming
Object-Oriented Programming (OOP) is a programming paradigm that organizes software
design around objects, rather than functions or logic. An object represents a real-world
entity that contains both data (attributes) and behavior (methods). Python supports OOP
completely and allows developers to write modular, reusable, secure, and scalable
applications.
OOP focuses on modeling real-world problems, making software easier to understand,
maintain, and extend.
1. Class and Object
Definition of Class
A class is a user-defined blueprint or template used to create objects. It defines:
Attributes (data members)
Methods (functions)
A class does not occupy memory until an object is created from it.
Definition of Object
An object is an instance of a class. It represents a real-world entity and occupies memory.
Each object has:
Identity
State
Behavior
Syntax of Class and Object in Python
class Student:
def display(self):
print("Welcome to Python OOP")
obj = Student()
[Link]()
Explanation
class Student: defines a class
self refers to the current object
obj = Student() creates an object of the class
[Link]() calls the method using the object
Real-World Analogy
Real World OOP
Car Blueprint Class
Actual Car Object
Color, Speed Attributes
Drive, Brake Methods
Characteristics of Class and Object
1. Encapsulation of data and behavior
2. Memory allocation occurs during object creation
3. Multiple objects can be created from a single class
4. Objects interact using method calls
Advantages of Class and Object
Promotes modular programming
Enhances reusability
Simplifies complex problem modeling
Supports scalability
Limitations
Slightly higher memory usage
Learning curve for beginners
2. Encapsulation
Definition
Encapsulation is the process of wrapping data and methods together into a single unit,
i.e., a class. It also involves restricting direct access to some components of an object to
protect data from unauthorized modification.
Encapsulation is achieved using access modifiers.
Access Modifiers in Python
Modifier Description
Public Accessible everywhere
Protected (_var) Accessible within class and subclasses
Private (__var) Accessible only within the class
Example of Encapsulation
class BankAccount:
def __init__(self, balance):
self.__balance = balance # private variable
def get_balance(self):
return self.__balance
def deposit(self, amount):
self.__balance += amount
Explanation
__balance is private
Direct access is restricted
Controlled access through methods
Importance of Encapsulation
1. Data Protection
2. Controlled Data Access
3. Improved Maintainability
4. Reduced Complexity
Real-World Example
An ATM machine:
User cannot access internal logic
Can only use provided operations (withdraw, deposit)
Advantages of Encapsulation
Improves security
Enhances code reliability
Reduces dependency
Easier debugging
Disadvantages
Slight increase in code complexity
Requires disciplined design
3. Inheritance
Definition
Inheritance allows a class (child/subclass) to acquire properties and methods of another class
(parent/superclass). It promotes code reusability and establishes a parent–child
relationship.
Types of Inheritance in Python
1. Single Inheritance
2. Multiple Inheritance
3. Multilevel Inheritance
4. Hierarchical Inheritance
5. Hybrid Inheritance
Syntax Example
class Animal:
def speak(self):
print("Animal makes a sound")
class Dog(Animal):
def bark(self):
print("Dog barks")
Explanation
Dog inherits from Animal
Dog can access speak() method
Real-World Example
Parent Child
Vehicle Car
Employee Manager
Benefits of Inheritance
1. Code reuse
2. Faster development
3. Easy extension
4. Reduced redundancy
Method Overriding (Concept Preview)
Child class can redefine parent methods.
Limitations
Tight coupling
Improper use increases complexity
4. Polymorphism
Definition
Polymorphism means “many forms”. It allows the same method name to perform different
tasks depending on the object calling it.
Types of Polymorphism in Python
1. Compile-time (Method Overloading – simulated)
2. Run-time (Method Overriding)
Example: Method Overriding
class Bird:
def fly(self):
print("Bird can fly")
class Penguin(Bird):
def fly(self):
print("Penguin cannot fly")
Explanation
Same method fly()
Different behavior based on object type
Built-in Polymorphism
print(len("Python"))
print(len([1, 2, 3]))
Advantages of Polymorphism
Flexibility
Code scalability
Reduced conditional logic
Cleaner architecture
Real-World Analogy
Object Action
Person Speak
Dog Bark
Cat Meow
Disadvantages
Difficult debugging
Requires strong design discipline
5. Abstraction
Definition
Abstraction hides internal implementation details and shows only essential features to the
user. It focuses on what an object does, not how it does it.
Abstraction in Python
Achieved using:
1. Abstract classes
2. Abstract methods
(abc module)
Example of Abstraction
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self):
pass
Explanation
Cannot create object of abstract class
Forces child classes to implement methods
Real-World Example
Mobile Phone:
User uses camera
Internal logic hidden
Advantages
Security
Reduces complexity
Improves maintainability
Encourages modular design
Disadvantages
Increased code length
Requires planning
6. Constructors and Destructors
Constructor (__init__)
Used to initialize object data.
class Student:
def __init__(self, name):
[Link] = name
Destructor (__del__)
Used to destroy objects.
def __del__(self):
print("Object destroyed")
Importance
Automatic memory handling
Resource management
7. Method Overriding
Definition
Redefining a parent class method in a child class.
class Parent:
def show(self):
print("Parent class")
class Child(Parent):
def show(self):
print("Child class")
Benefits
Runtime polymorphism
Customized behavior
8. Multiple Inheritance
Definition
A class inheriting from more than one parent class.
class A:
def displayA(self):
print("Class A")
class B:
def displayB(self):
print("Class B")
class C(A, B):
pass
Method Resolution Order (MRO)
Python uses C3 linearization to resolve conflicts.
print([Link]())
Advantages
Code reuse
Powerful design
Disadvantages
Complexity
Diamond problem
Object-Oriented Programming in Python provides a robust, scalable, and secure
approach to software development. Concepts like encapsulation, inheritance,
polymorphism, and abstraction form the backbone of modern application development and
are essential for professional programming.
MODULE 6: EXCEPTION HANDLING AND FILE HANDLING
6.1 Types of Errors
Introduction to Errors in Python
In programming, an error is a condition that disrupts the normal flow of program execution.
Errors occur due to incorrect syntax, logical mistakes, improper input, or unexpected runtime
conditions. Python, being an interpreted language, detects errors either during compilation
(interpretation) or during execution.
Understanding the types of errors is critical for:
writing robust programs
debugging efficiently
developing fault-tolerant applications
Classification of Errors
Errors in Python are broadly classified into:
1. Syntax Errors
2. Runtime Errors
3. Logical Errors
6.1.1 Syntax Errors
Definition
A Syntax Error occurs when the Python interpreter finds code that does not conform to the
grammatical rules of the Python language. These errors are detected before execution.
Causes of Syntax Errors
Missing colon (:)
Improper indentation
Misspelled keywords
Missing parentheses
Invalid assignment statements
Example
if x > 5
print("Hello")
Error Output:
SyntaxError: invalid syntax
Explanation
The if statement must end with a colon.
Python cannot proceed without syntactically valid code.
Characteristics of Syntax Errors
Detected at compile time
Program does not execute at all
Easy to identify due to explicit error messages
6.1.2 Runtime Errors
Definition
A Runtime Error occurs while the program is executing, even though the syntax is correct.
These errors are also known as exceptions.
Common Runtime Errors in Python
Error Type Cause
ZeroDivisionError Division by zero
NameError Undefined variable
TypeError Invalid operation between types
ValueError Invalid value
IndexError Invalid index access
KeyError Missing dictionary key
Example
x = 10 / 0
Error Output:
ZeroDivisionError: division by zero
Characteristics
Occur during execution
Program terminates abruptly
Can be handled using exception handling
6.1.3 Logical Errors
Definition
A Logical Error occurs when a program runs successfully but produces incorrect output due
to faulty logic.
Example
a = 10
b = 20
print(a - b) # intended addition
Output:
-10
Characteristics
No error message
Hardest to detect
Requires debugging and testing
Importance of Error Classification
Understanding error types helps programmers:
apply correct debugging strategies
decide when to use exception handling
improve program reliability
6.2 Exception Handling
Concept of Exception Handling
Exception Handling is a mechanism that allows a program to handle runtime errors
gracefully, without terminating execution abruptly. Python provides a structured way to
catch and respond to exceptions using predefined constructs.
Why Exception Handling Is Needed
Prevents program crashes
Improves user experience
Ensures continuity of execution
Enables recovery from errors
Supports robust application development
Python Exception Handling Constructs
Python uses the following keywords:
try
except
else
finally
6.3 try Block
Definition
The try block contains code that may generate an exception. Python monitors this block for
errors.
Syntax
try:
risky_code
Example
try:
x = int(input("Enter a number: "))
print(10 / x)
Explanation
If x is zero or invalid, an exception occurs
Control immediately transfers to except
Rules of try Block
Must be followed by at least one except or finally
Cannot exist alone
Multiple exceptions may occur within a single try block
6.4 except Block
Definition
The except block handles the exception raised in the try block.
Syntax
except ExceptionType:
handling_code
Example
try:
x = 10 / 0
except ZeroDivisionError:
print("Division by zero is not allowed")
Multiple except Blocks
try:
a = int("abc")
except ValueError:
print("Invalid value")
except TypeError:
print("Type error")
Generic Exception Handling
except Exception as e:
print(e)
Best Practices
Catch specific exceptions
Avoid blanket except unless necessary
Log error details for debugging
6.5 else Block
Definition
The else block executes only if no exception occurs in the try block.
Syntax
try:
code
except:
error_handling
else:
success_code
Example
try:
x = int(input())
except ValueError:
print("Error")
else:
print("Valid input")
Advantages
Improves readability
Separates error logic from success logic
6.6 finally Block
Definition
The finally block executes regardless of whether an exception occurs or not.
Purpose
Resource cleanup
Closing files
Releasing memory
Database disconnection
Example
try:
file = open("[Link]", "r")
print([Link]())
except FileNotFoundError:
print("File not found")
finally:
print("Execution completed")
Characteristics
Always executes
Used for cleanup tasks
Ensures consistency
6.7 Custom Exceptions
Definition
Custom Exceptions are user-defined exceptions that allow programmers to create
meaningful error conditions specific to application logic.
Why Custom Exceptions Are Needed
Application-specific error handling
Improved clarity
Domain-driven design
Cleaner exception hierarchy
Creating a Custom Exception
class InvalidAgeError(Exception):
pass
Raising Custom Exceptions
def check_age(age):
if age < 18:
raise InvalidAgeError("Age must be 18 or above")
Handling Custom Exceptions
try:
check_age(15)
except InvalidAgeError as e:
print(e)
Advantages
Better error categorization
Cleaner business logic
Easier debugging
6.8 File Handling
Introduction to File Handling
File handling enables programs to store data permanently. Python provides built-in support
for file operations such as:
creating files
reading files
writing files
appending files
Types of Files
1. Text files (.txt)
2. Binary files (.bin)
3. CSV files (.csv)
4. JSON files (.json)
File Modes
Mode Description
r Read
w Write
a Append
rb Read binary
wb Write binary
6.9 Reading Files
Opening a File
file = open("[Link]", "r")
Reading Methods
read()
readline()
readlines()
Example
file = open("[Link]", "r")
print([Link]())
[Link]()
Using with Statement
with open("[Link]", "r") as file:
print([Link]())
Advantages of with Statement
Automatic file closing
Prevents resource leaks
Cleaner syntax
6.10 Writing Files
Writing to a File
file = open("[Link]", "w")
[Link]("Hello Python")
[Link]()
Appending Data
file = open("[Link]", "a")
[Link]("\nNew Line")
[Link]()
Handling Overwrite Risks
w mode clears file content
Use a mode for safety
6.11 Working with CSV Files
Introduction to CSV
CSV (Comma Separated Values) files store tabular data in plain text format.
CSV Module in Python
import csv
Writing CSV Files
with open("[Link]", "w", newline="") as file:
writer = [Link](file)
[Link](["Name", "Age"])
[Link](["Alice", 25])
Reading CSV Files
with open("[Link]", "r") as file:
reader = [Link](file)
for row in reader:
print(row)
Advantages of CSV
Lightweight
Human-readable
Widely supported
6.12 Working with JSON Files
Introduction to JSON
JSON (JavaScript Object Notation) is a lightweight data interchange format used for
structured data storage and exchange.
JSON Module
import json
Writing JSON Data
data = {"name": "John", "age": 30}
with open("[Link]", "w") as file:
[Link](data, file)
Reading JSON Data
with open("[Link]", "r") as file:
data = [Link](file)
print(data)
Advantages of JSON
Structured
Language-independent
Ideal for APIs and configuration files
MODULE 7: PYTHON MODULES AND PACKAGES
7.1 Introduction to Python Modules
In Python, as programs grow in size and complexity, it becomes difficult to manage all code
in a single file. To overcome this limitation, Python provides the concept of modules. A
module is a file containing Python code such as functions, classes, and variables that can be
reused across multiple programs.
Modules promote modularity, reusability, maintainability, and organized programming.
Python follows a modular programming approach, which allows developers to divide large
programs into smaller, manageable units.
7.2 Importing Modules
Definition
Importing modules refers to the process of accessing code written in one Python file from
another Python program.
Python provides multiple ways to import modules depending on usage requirements.
7.2.1 import Statement
Syntax:
import math
print([Link](25))
Explanation:
Imports the entire math module
Functions are accessed using dot (.) notation
7.2.2 import with Alias
Syntax:
import math as m
print([Link])
Advantages:
Shorter names
Improves readability
Avoids naming conflicts
7.2.3 from…import Statement
Syntax:
from math import sqrt
print(sqrt(16))
Explanation:
Imports specific functions
No need for module name prefix
7.2.4 from…import *
Syntax:
from math import *
print(sin(90))
Disadvantage:
Namespace pollution
Reduced code clarity
Best Practices for Importing Modules
Use explicit imports
Avoid wildcard imports
Group standard, third-party, and user-defined imports separately
7.3 Standard Library Overview
Definition
The Python Standard Library is a collection of pre-built modules that provide
solutions for common programming tasks without requiring additional installation.
Common Standard Library Modules
Module Purpose
math Mathematical operations
sys System-specific parameters
os Operating system interaction
datetime Date and time handling
random Random number generation
json JSON file handling
csv CSV file operations
re Regular expressions
Example: os Module
import os
print([Link]())
Advantages of Standard Library
No external installation required
Highly optimized and tested
Cross-platform compatibility
Saves development time
7.4 Creating User-defined Modules
Definition
A user-defined module is a Python file created by the programmer to store reusable code.
Creating a Module
File: [Link]
def add(a, b):
return a + b
def subtract(a, b):
return a - b
Using the Module
import calculator
print([Link](5, 3))
Advantages of User-defined Modules
Code reusability
Better organization
Easy maintenance
Separation of concerns
Module Search Path
Python searches modules in the following order:
1. Current directory
2. PYTHONPATH
3. Standard library directories
7.5 Packages and Virtual Environments
Definition of Package
A package is a collection of related modules organized in directories. It allows hierarchical
structuring of modules.
Package Structure
mypackage/
│
├── __init__.py
├── [Link]
└── [Link]
Importing from a Package
from mypackage import module1
Advantages of Packages
Logical grouping of modules
Avoids naming conflicts
Supports large-scale projects
7.6 Virtual Environments
Definition
A virtual environment is an isolated Python environment that allows different projects to
use different versions of libraries without conflict.
Creating a Virtual Environment
python -m venvmyenv
Activating Virtual Environment
Windows:myenv\Scripts\activate
Linux/Mac: source myenv/bin/activate
Importance of Virtual Environments
Dependency isolation
Version control
Clean development setup
Prevents system-wide conflicts
MODULE 8: DATABASE FUNDAMENTALS
8.1 Introduction to Databases
Definition
A database is an organized collection of data that allows efficient storage, retrieval, and
manipulation of information.
Databases are essential for applications that handle large volumes of structured data such as:
banking systems
e-commerce platforms
student information systems
Need for Databases
Efficient data storage
Fast retrieval
Data consistency
Multi-user access
Data security
8.2 DBMS vs RDBMS
DBMS (Database Management System)
A DBMS is software that manages data in a database without enforcing relationships between
data.
Examples: File systems, XML databases
RDBMS (Relational Database Management System)
An RDBMS stores data in the form of tables (relations) and enforces relationships using
keys.
Examples: MySQL, PostgreSQL, Oracle, SQL Server
Comparison Table
Feature DBMS RDBMS
Data storage Files Tables
Relationships No Yes
Normalization Not supported Supported
Data integrity Low High
Examples File system MySQL
8.3 SQL Basics
Definition of SQL
SQL (Structured Query Language) is a standard language used to interact with relational
databases.
Categories of SQL Commands
8.3.1 DDL (Data Definition Language)
Used to define database structure.
Command Purpose
CREATE Create tables
ALTER Modify structure
DROP Delete objects
Command Purpose
TRUNCATE Remove data
Example:
CREATE TABLE Student (
id INT,
name VARCHAR(50)
);
8.3.2 DML (Data Manipulation Language)
Used to manipulate data.
Command Purpose
INSERT Add records
UPDATE Modify records
DELETE Remove records
SELECT Retrieve data
8.3.3 DCL (Data Control Language)
Used to control access.
Command Purpose
GRANT Provide access
REVOKE Remove access
8.3.4 TCL (Transaction Control Language)
Used to manage transactions.
Command Purpose
COMMIT Save changes
ROLLBACK Undo changes
SAVEPOINT Set transaction point
8.4 Constraints and Keys
Constraints
Constraints enforce rules on table data to ensure integrity.
Constraint Description
NOT NULL Prevents null values
UNIQUE Ensures uniqueness
PRIMARY KEY Unique + not null
FOREIGN KEY Maintains relationships
CHECK Validates conditions
DEFAULT Sets default value
Keys
Keys uniquely identify records in a table.
Key Type Description
Primary Key Unique identifier
Foregn Key References another table
Candidate Key Potential primary key
Composite Key Combination of columns
8.5 Joins and Subqueries
Joins
Joins combine rows from two or more tables based on a related column.
Types of Joins
Join Type Description
INNER JOIN Matching records
LEFT JOIN All left table records
RIGHT JOIN All right table records
FULL JOIN All records
Example: INNER JOIN
SELECT [Link], [Link]
FROM Student
INNER JOIN Course
ON [Link] = [Link];
Subqueries
A subquery is a query nested inside another query.
Example
SELECT name
FROM Student
WHERE marks > (SELECT AVG(marks) FROM Student);
Advantages of Joins and Subqueries
Efficient data retrieval
Complex data analysis
Reduced redundancy
Modules and databases form the backbone of scalable Python applications. Understanding
modules, packages, SQL, and relational concepts is essential for full-stack development,
data engineering, and backend systems.
MODULE 9: DATABASE CONNECTIVITY WITH PYTHON
9.1 Introduction to DB-API
The Python Database API (DB-API) is a standardized specification that defines how Python
programs communicate with relational database management systems (RDBMS). It was
introduced under PEP 249 to ensure consistency across different database drivers such as
SQLite, MySQL, and PostgreSQL.
DB-API acts as an interface layer between Python applications and database engines.
Without DB-API, each database vendor would require a completely different syntax and
approach, increasing complexity and reducing portability. By following DB-API standards,
developers can switch databases with minimal changes to application logic.
DB-API defines:
Methods for connecting to databases
Cursor objects for executing SQL queries
Standard exception hierarchy
Transaction control mechanisms
The DB-API follows a connection–cursor–execution model. A connection object establishes
communication with the database, while a cursor object executes SQL commands and fetches
results.
Table 1: Core DB-API Components
Component Description
Connection Represents database connection
Cursor Executes SQL statements
execute() Runs SQL queries
fetchone() Fetches one record
fetchall() Fetches all records
Table 2: DB-API Exception Hierarchy
Exception Meaning
DatabaseError Base database error
IntegrityError Constraint violation
OperationalError Connection issues
ProgrammingError SQL syntax errors
9.2 SQLite / MySQL / PostgreSQL Connectivity
Python supports connectivity with multiple databases through DB-API–compliant drivers.
The most commonly used databases are SQLite, MySQL, and PostgreSQL, each serving
different application needs.
SQLite is a lightweight, file-based database included with Python. It is ideal for small
applications, prototypes, and embedded systems.
MySQL is a widely used open-source RDBMS suitable for web applications.
PostgreSQL is an advanced, enterprise-grade database with strong support for transactions,
concurrency, and data integrity.
Database connectivity typically follows these steps:
1. Import database module
2. Establish connection
3. Create cursor
4. Execute SQL statements
5. Commit changes
6. Close connection
Table 1: Python Database Drivers
Database Python Module
SQLite sqlite3
MySQL mysql-connector-python
PostgreSQL psycopg2
Table 2: Connectivity Comparison
Feature SQLite MySQL PostgreSQL
Installation Built-in External External
Scalability Low Medium High
Use Case Small apps Web apps Enterprise
9.3 CRUD Operations using Python
CRUD operations represent the fundamental actions performed on database records:
Create
Read
Update
Delete
Python executes CRUD operations by sending SQL commands through cursor objects. Each
operation corresponds to a specific SQL statement. CRUD operations are the backbone of all
database-driven applications, including student systems, banking platforms, and e-commerce
websites.
The reliability of CRUD operations depends on:
Correct SQL syntax
Proper transaction handling
Error management using exceptions
Table 1: CRUD Operation Mapping
Operation SQL Command
Create INSERT
Read SELECT
Operation SQL Command
Update UPDATE
Delete DELETE
Table 2: Example CRUD Scenarios
Scenario Operation
Add student record Create
View marks Read
Modify address Update
Remove account Delete
9.4 Parameterized Queries
Parameterized queries are SQL queries that use placeholders instead of embedding values
directly into SQL statements. They are a critical security feature that prevents SQL Injection
attacks.
In parameterized queries:
SQL structure is predefined
Data values are supplied separately
Database engine safely escapes inputs
This approach improves:
Security
Query performance
Code readability
Maintainability
Parameterized queries are mandatory in production-grade applications, especially when
handling user input such as login credentials or form submissions.
Table 1: Query Types Comparison
Query Type Risk Level
Dynamic SQL High
Parameterized SQL Low
Table 2: Placeholder Styles
Database Placeholder
SQLite ?
MySQL %s
PostgreSQL %s
9.5 ORM Basics (Introduction to SQLAlchemy)
An Object Relational Mapper (ORM) allows developers to interact with databases using
Python objects instead of raw SQL queries. SQLAlchemy is the most popular ORM library
in Python.
ORM maps:
Tables → Classes
Rows → Objects
Columns → Attributes
Using ORM:
Reduces SQL complexity
Improves code maintainability
Supports database independence
SQLAlchemy provides two layers:
1. Core (SQL expression language)
2. ORM (high-level abstraction)
ORM is especially useful in large applications where frequent database interactions occur.
Table 1: SQL vs ORM Comparison
Aspect SQL ORM
Complexity High Low
Readability Moderate High
Flexibility High Moderate
Table 2: SQLAlchemy Components
Component Purpose
Engine Database connection
Session Transaction handling
Component Purpose
Model Table mapping
Query Data retrieval
MODULE 10: WEB FUNDAMENTALS
10.1 How the Web Works
The World Wide Web (WWW) is a system of interlinked resources accessed over the
internet using standard protocols. The web works on a request–response model, where
clients request resources and servers respond with data.
When a user enters a URL:
1. DNS resolves domain to IP address
2. Browser sends HTTP request
3. Server processes request
4. Response is sent back
5. Browser renders content
This process happens in milliseconds and involves multiple layers such as networking,
protocols, and rendering engines.
Table 1: Web Components
Component Role
Browser Sends request
DNS Resolves domain
Server Sends response
Table 2: Types of Web Resources
Resource Example
Static HTML, CSS
Resource Example
Dynamic APIs
Media Images, videos
10.2 Client-Server Architecture
Client-server architecture divides responsibilities between two entities:
Client: Requests services
Server: Provides services
This model enables:
Centralized data management
Scalability
Security
Concurrent access
Client Server Architecture
Clients can be browsers, mobile apps, or desktop applications. Servers manage
databases, business logic, and authentication.
Table 1: Client vs Server Roles
Client Server
Sends requests Processes requests
User interface Business logic
Table 2: Architecture Types
Type Description
Two-tier Client–DB
Three-tier Client–Server–DB
Type Description
10.3 HTTP/HTTPS Protocol
HTTP (HyperText Transfer Protocol) is the foundation of data communication on the web.
It is a stateless protocol, meaning each request is independent.
HTTPS is the secure version of HTTP, using SSL/TLS encryption to protect data.
HTTP methods define actions:
GET
POST
PUT
DELETE
Table 1: HTTP Methods
Method Purpose
GET Retrieve data
POST Submit data
PUT Update data
DELETE Remove data
Table 2: HTTP vs HTTPS
Feature HTTP HTTPS
Security No Yes
Encryption No SSL/TLS
Port 80 443
10.4 Web Servers
A web server is software that receives HTTP requests and delivers web content. It handles:
Request routing
Static file serving
Load handling
Security configurations
Popular web servers include Apache, Nginx, and IIS. In Python-based applications, web
servers often work alongside frameworks like Flask or Django.
Table 1: Popular Web Servers
Server Characters
Apache Flexible
Nginx High performance
IIS Windows-based
Table 2: Web Server Responsibilities
Task Description
Request handling Process HTTP
Load balancing Traffic distribution
10.5 RESTful Architecture Basics
REST (Representational State Transfer) is an architectural style for designing networked
applications. RESTful systems use standard HTTP methods and are stateless.
Key REST principles:
Statelessness
Resource-based URLs
Uniform interface
Client-server separation
REST is widely used in modern APIs due to its simplicity and scalability.
Restful Web server
Table 1: REST Principles
Principle Description
Stateless No session storage
Resource-based URL-based access
Table 2: REST vs SOAP
Aspect REST SOAP
Complexity Low High
Data format JSON XML
Performance Fast Slower