0% found this document useful (0 votes)
3 views113 pages

Python Syllabus

Uploaded by

ahmadadaakif
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views113 pages

Python Syllabus

Uploaded by

ahmadadaakif
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

PYTHON SYLLABUS

1
SESSION 1: PYTHON – Introduction & SESSION 14 : PYTHON CGI INTRODUCTION –
Installation in Python Writing python program for CGI applications

SESSION 2 : PYTHON – input &output, SESSION 15:SMTP – Sending email sending


varaiables , Data types , Type Conversion an HTML e-mail using python , Sending
Attachments as an E-mail

SESSION 3 : DATATYPES IN PYTHON – Basic SESSION 16 : REGULAR EXPRESSION –


data types : int , float , string , Boolean & Pattern matching , searching , Real time
Complex , List ,Tuple , String , Dictionary , Set parsing of networking or system data using
regex , validation concepts
SESSION 4 :FUNCTIONS –Types of Functions , SESSION 17 : REAL TIME HACK – Web
Function with Arguments , Recursion , Global Scraping , Chatbot & Language , Translate ,
,Local & non Local , lambda Function Find the Similarity ratio between text
SESSION 5: BUILT-IN-FUNCTION – math,
String & Date Functions and Operations , PDF
extraction , CSV Module SESSION 18 : Tagging Sentence to find key
word , Bubble sort algorithm , qr code
generator

SESSION 6: FLOW CONTROL – Operators , SESSION 19 : Spell Checker , Scaping


Conditional Statements , Loopings , Break WIKIPEDIA , Anagram & Screenshot app
and Continue

SESSION 7 : MODULES & PACKAGES – SESSION 20 : Python for networking , getting


Creating module , Using Module , Create a input from user
Package , import and use modules from
package

SESSION 8 : PYTHON FILE OPEATION –Opening


files : Open(), Writing files : write() and Write
lines() , Reading files : read() , read line(),read SESSION 21: SERVER CLIENT PROGRAM –
lines(), closing files : close (), Manipulating file Introduction to Django , Django and Python ,
pointer , file operations MVC : model , view , static Template
SESSION 9 : DIRECTORIES – Current working SESSION 22: GETTING STARTED WITH
directory , changing directory ,list directoy , DJANGO – template files – Http Response ,
Making a new directory , Renaming a HTML page rendering
directory , Removing s directory or file

2
SESSION 10 : EXCEPTION HANDLING – SESSION 23 : STATIC FILES – Adding CSS and
try,Except and Finally ,Try else , Custom images , Anchor tag creation
Exception , Error vs Exception

SESSION 11 : OOPS CONCEPT – Class and


Objects , Inheritance , Encapsulation ,
Polymorphism , Data Abstraction , SESSION 24 : DJANGO DATABASE
Overloading , Overriding Dynamic CONNECTIVITY MYSQL – (CRUD Operation) –
Creating Database and Table Insert the data ,
Fetching the data from database , update the
data , delete the data

SESSION 12 : MULTITHREADING – SESSION 25: MAIL SENDING – Database


Understanding threads , Forking threads m Connectivity with mail sending
Synchronizing
SESSION 13: PYTHON DATABASE SESSION 26 : USER AUTHENTICATION – User
CONNECTIVITY – MYSQL and MongoDB authentication Register and login
Database connection using python , CRUD
Operations, Queries in MYSQL

3
4
PYTHON

1. Introduction to Python

Python is a high-level, interpreted programming language known for its readability and
versatility. Created by Guido van Rossum in 1991, it's widely used in:

 Web Development
 Data Science
 Automation
 Artificial Intelligence
 Scientific Computing

Key Features:

 Easy to learn and read


 Cross-platform compatibility
 Extensive library support
 Open-source and community-driven

2. Installation & IDLE Setup

Step-by-Step Installation:

1. Download Python:
o Visit [Link]
o Click "Downloads" → Choose your OS (Windows/Mac/Linux)
2. Install Python:
o Run the installer
o IMPORTANT: Check "Add Python to PATH"
o Click "Install Now"
3. Verify Installation:
Open Command Prompt/Terminal:
python --version

[Link] IDLE (Python's IDE):

5
o Search for "IDLE" in Start Menu
o Opens interactive Python shell
o File → New File to create scripts

3. Input & Output Operations

Understanding Input and Output in Python

Input: Getting data from the user or external sources


Output: Displaying results to the user or saving to files

Static Output:

print("Hello, World!")
print("Python", "Programming", sep="-")
print("Line 1", end=" ")
print("Line 2 continues")
name = "Alice"
age = 20
print("Student Name:", name, "Age:", age)

6
Dynamic Input:

# Taking user input


name = input("Enter your name: ")
age = int(input("Enter your age: "))

print(f"Hello {name}, you are {age} years old")


print(“Hello”+name+”you are”+str(age)+”years old”)

4. Variables & Data Types


What are Variables?

Variables are containers that store data values. Think of them as labeled boxes where you can
put different types of information.

# Variable assignment
counter = 100 # Integer
miles = 1000.0 # Float
name = "John" # String
is_valid = True # Boolean

DATATYPES:

1. Numeric Types: int and float

 int (Integer): Positive or negative whole numbers without decimals.


 float (Floating Point): Numbers that contain decimal points.

# Static Example Code


age = 25 # int
price = 99.99 # float

print(type(age)) # Output: <class 'int'>


print(type(price)) # Output: <class 'float'>

#Dynamic Input
age = int(input(“enter your age :”))
price =float(input(“enter a price :”))

print(type(age)) # Output: <class 'int'>


print(type(price)) # Output: <class 'float'>

7
Scenario: A simple ATM withdrawal system.

 Static Example:

Python

balance = 5000 # int


withdrawal = 200.50 # float
remaining = balance - withdrawal
print("Static Balance:", remaining)

 Dynamic Example:

Python

balance = int(input("Enter current balance: "))


withdrawal = float(input("Enter withdrawal amount: "))
print(f"Updated Balance: {balance - withdrawal}")

2. String (str)

Concept: Textual data and it starts and end with (“”).

Scenario: A personalized welcome greeting.

 Static Example:

greeting = "Hello"
name = "Student"
message = greeting + " " + name
print(message)

 Dynamic Example:

user_name = input("Please enter your name: ")


print("Welcome to the Python class, " + user_name + "!")

8
3. Boolean (bool)

Concept: Logical True(1) or False(0)

. Scenario: Checking if a student passed.

 Static Example:

is_sunny = True
is_raining = False
print("Is it a clear day?", is_sunny)

 Dynamic Example:

score = int(input("Enter your exam score: "))


passed = score >= 50
print("Did you pass the exam?", passed)

[Link] []

Properties: Ordered, Mutable (Changeable), Allows Duplicates.

 append(item): Adds an item to the end of the list.


 insert(index, item): Adds an item at a specific position.
 remove(item): Removes the first occurrence of a specific value.
 pop(): Removes and returns the last item (or an item at a specific index).

Static Example:

fruits = ["apple", "banana"]


[Link]("cherry") # adds to end
[Link](1, "orange") # adds at index 1
[Link]("apple") # deletes apple
print(fruits) # Output: ['orange', 'banana', 'cherry']

Dynamic Example:

my_list = ["Book", "Pen"]


new_item = input("Enter item to add: ")
my_list.append(new_item)
print("Updated list:", my_list)

9
. [Link] ()

Properties: Ordered, Immutable (Unchangeable), Allows Duplicates.

 Note: Because tuples are immutable, you cannot append, add, or remove items once
created. You can only access items or delete the entire tuple.
 count(item): Returns the number of times a value occurs.
 index(item): Returns the position of a value.

Static Example:

colors = ("red", "blue", "red")


print([Link]("red")) # Output: 2
print(colors[1]) # Output: blue

6. Set {}

Properties: Unordered, Mutable, No Duplicates Allowed.

 add(item): Adds an element to the set (if it doesn't already exist).


 remove(item): Removes an item. Raises an error if the item is not found.
 discard(item): Removes an item. Does not raise an error if item is missing.
 clear(): Removes all elements from the set.

Static Example:

tags = {"python", "coding"}


[Link]("ai") # adds ai
[Link]("python") # does nothing (already exists)
[Link]("coding")
print(tags) # Output: {'python', 'ai'}

Dynamic Example:

user_set = {"admin", "guest"}


new_user = input("Enter new username: ")
user_set.add(new_user)
print("Unique users:", user_set)

10
7. Dictionary {"key": "value"}

Properties: Ordered , Mutable, Keys must be Unique.

 update({key: value}): Adds or updates elements.


 pop(key): Removes the item with the specified key name.
 keys(): Returns a list of all keys.
 values(): Returns a list of all values.

Static Example:

car = {"brand": "Ford", "year": 2020}


car["color"] = "Red" # Adding a new key-value pair
[Link]({"year": 2022}) # Updating existing key
[Link]("brand") # Removing key 'brand'
print(car) # Output: {'year': 2022, 'color': 'Red'}

Dynamic Example:

student = {"name": "Alice"}


info_type = input("What info do you want to add? (e.g., Grade): ")
info_val = input(f"Enter the value for {info_type}: ")
student[info_type] = info_val
print("Final Student Data:", student)

Complex Data Type (complex)

The Formula

A complex number is written in the form:

a + bj

 a: The Real part.


 bj: The Imaginary part.

Static Example

In a static example, we define the complex number directly in the code.

11
# Defining complex numbers
z1 = 3 + 5j
z2 = 2 + 3j

# Addition
result = z1 + z2

print("Complex Number 1:", z1)


print("Real Part:", [Link]) # Output: 3.0
print("Imaginary Part:", [Link]) # Output: 5.0
print("Sum of Complex Numbers:", result) # Output: (5+8j)

Dynamic Example

In a dynamic example, we take user input. Since input() returns a string, we use the complex()
constructor to convert it.

# Taking user input for complex numbers


val1 = input("Enter first complex number (e.g., 2+3j): ")
val2 = input("Enter second complex number (e.g., 1+1j): ")

# Converting string to complex type


c1 = complex(val1)
c2 = complex(val2)

# Performing multiplication
product = c1 * c2

print(f"The product of {c1} and {c2} is: {product}")

TYPE CONVERSION

Type Conversion (also known as Type Casting) is the process of converting a value from one
data type to another. In Python, this is essential because certain operations (like adding a
number to a string) will cause errors unless the types match.

There are two types of conversion:

1. Implicit: Handled automatically by Python.


2. Explicit: Handled manually by the programmer using built-in functions.

12
1. Integer Conversion (int)

Converts a float or a compatible string into an integer.

 Static Example:

price = 99.99
converted_price = int(price) # Truncates decimals
print("Static Integer:", converted_price) # Output: 99

 Dynamic Example:

age_input = input("Enter your age: ")


# input() always returns a string, so we must convert it to do math
age = int(age_input)
print("In 5 years, you will be:", age + 5)

2. Float Conversion (float)

Converts an integer or a compatible string into a decimal number.

 Static Example:

whole_number = 10
decimal_number = float(whole_number)
print("Static Float:", decimal_number) # Output: 10.0

 Dynamic Example:

weight = input("Enter weight in kg: ")


# Converting to float allows users to enter 70 or 70.5
final_weight = float(weight)
print("Weight recorded as:", final_weight)

3. String Conversion (str)

Converts numbers or collections into text. This is often used for joining text with numbers
(concatenation).

 Static Example:

score = 100

13
message = "Your score is " + str(score)
print(message) # Output: Your score is 100

 Dynamic Example:

year = int(input("Enter birth year: "))


current_year = 2025
result = "You are " + str(current_year - year) + " years old."
print(result)

4. Collection Conversion (list, tuple, set)

You can convert between different types of collections to change their properties (e.g.,
converting a List to a Set to remove duplicates).

 Static Example:

# Convert Tuple to List to make it changeable


coordinates_tuple = (10, 20)
coord_list = list(coordinates_tuple)
coord_list.append(30)
print("Updated List:", coord_list)

 Dynamic Example:

# Taking multiple values from user and converting to a Set to get unique items

user_input = input("Enter items separated by space: ")


items_list = user_input.split() # Creates a list
unique_items = set(items_list) # Converts list to set
print("Your unique items are:", unique_items)

FUNCTIONS :

1. What is a Function?
A function is a reusable block of code that performs a specific task. Functions help organize
code, avoid repetition, and make programs easier to read and maintain. In Python functions are
defined using the 'def' keyword.

14
Basic syntax:
def function_name(parameters):
return value
Example and explanation:
def greet():
print("Hello, World!")

greet() #calling that function


Output:
Hello, World!

Explanation: 'greet' is a user-defined function with no parameters that prints a message when
called.
2. Types of Functions
Functions in Python can be grouped into several categories:

 Built-in functions: Provided by Python (e.g., print(), len(), type()).


 User-defined functions: Created by programmers using def.
 Anonymous (lambda) functions: Small unnamed functions defined with lambda.
 Higher-order functions: Functions that take other functions as arguments or return
functions.

Built-in function

 Functions that are pre-defined in Python, such as print(), len(), range(), and type().

Example :
print(len("Python")) # Output: 6
print(type(“python”)) #Output : <class ‘str’>
User-Defined Functions:
 Functions created by the programmer using the def keyword to perform specific tasks.

Example :
Static Example :
def add(a, b):
return a + b

15
print(add(3,4)) # Output: 7
Dynamic Example :
def add(a, b):
return a + b
a=int(input(“enter A value : ”))
b=int(input(“enter B value : ”))

print(add(a,b))

Lambda Functions

A Lambda function is a small, anonymous function (a function without a name). It can take any
number of arguments but can only have one expression.

 Syntax: lambda arguments : expression


 Static Example:

square = lambda x: x * x
print(square(10)) # Output: 100

 Dynamic Example:

power = int(input("Enter power: "))


calc = lambda n: n ** power
num = int(input("Enter number: "))
print("Result:", calc(num))

Higher-order functions

Functions that take functions as arguments or return functions (map, filter, or user functions)

HOF taking function as argument

Example:

def square(n):
return n * n

16
def apply(func, value): /// arguments
return func(value)

result = apply(square, 5)
print(result) //25

Explanation :

 square is a function that squares a number.


 apply takes two arguments: a function (func) and a value (value).
 Inside apply, it calls func(value) → square(5) → 25
 Prints 25

HOF that returns a function

Example:

def make_multiplier(n):
def multiply(x):
return x * n
return multiply

double = make_multiplier(2)
triple = make_multiplier(3)

print(double(5)) # 10
print(triple(5)) # 15

Explanation

 make_multiplier(n) returns a new function multiply(x).


 double = make_multiplier(2) → new function multiply(x) = x*2
 double(5) → 5*2 = 10
 triple(5) → 5*3 = 15

Functions with Arguments


Functions become powerful when they accept input values (arguments). Python
supports several argument types:
1. Positional arguments
2. Keyword arguments

17
3. Default arguments
4. Variable-length arguments (*args and **kwargs)

Positional Arguments
Positional arguments are passed in order and matched to parameters by position.
def multiply(a, b):
return a * b

print(multiply(4, 2))
print(multiply(5, 5))
# Output: 12
Explanation: 3 maps to a and 4 maps to b by position.
Keyword Arguments
Keyword arguments are passed using parameter names. Order doesn't matter.
def student(name, age):
print(name, "is", age, "years old")

student(age=21, name='Riya') // student(name='Riya',age=21) # Output: Riya is 21 years old


Explanation: Parameters are assigned explicitly by name.
Default Arguments
Default arguments provide default values when arguments are omitted.
def greet(name='User'):
print('Hello', name)

greet( ) # Output: Hello User


greet('Amit') # Output: Hello Amit
Explanation: When no argument is passed, the default 'User' is used.
Variable-length Arguments (*args, **kwargs)
*args allows sending a variable number of positional arguments. **kwargs(key/pair) allows
variable keyword arguments.
Example
def total(*nums):

18
print(nums) # shows what Python collected
return sum(nums)
print(total(1, 2, 3))
-------------------------------------------------------------------------------------------------------------------------------

def add_numbers(*nums):
return sum(nums)
print(add_numbers(5, 10))
print(add_numbers(1,2,3,4,5)
-------------------------------------------------------------------------------------------------------------------------------
Example for **kwargs
def show_info(**info):
for key, value in [Link]():
print(key, "=", value)
show_info(name='Amit', city='Delhi', age=30)

Using Both *args and **kwargs Together


def fun(*args, **kwargs):
print("args:", args)
print("kwargs:", kwargs)

fun(1,2,3, name="Riya", age=21)

Explanation: *args collects extra positional args as a tuple; **kwargs collects named args as a
dictionary.
Return Values and Multiple Returns
Functions can return values to the caller. Python functions can return multiple values (as a
tuple).
def add(a, b):
return a + b
result = add(5, 3)
print(result) #8
19
def stats(a, b):
s=a+b
p=a*b
return s, p

sum_val, product_val = stats(4,5)


print(sum_val) # Output: 9
print(product_val) # Output: 20 (9,20)
Explanation: Multiple values are packed into a tuple and can be unpacked when returned.
-------------------------------------------------------------------------------------------------------------------------------
Recursion
Recursion is when a function calls itself. It's a natural fit for problems that can be divided into
similar subproblems .Every recursive function needs a base case (Condition) to stop recursion;
otherwise it will cause infinite recursion and a RecursionError.
Example 1: Factorial
def factorial(n):
if n == 0 or n == 1:
return 1
return n * factorial(n-1)

print(factorial(5)) # Output: 120


Explanation:
factorial(5)
=> 5 * factorial(4(n-1))
=> 5 * 4 * factorial(3)
= > 5 * 4 * 3 * factorial(2)
= > 5 * 4 * 3 * 2 * factorial(1)
=> 5 * 4 * 3 * 2 * 1
= 120

20
Example 2: Fibonacci (simple recursive version)
def fib(n):
if n <= 1:
return n
return fib(n-1) + fib(n-2)

print(fib(6)) # Output: 8
Explanation:

 fib(0) = 0
 fib(1) = 1
 For n ≥ 2: fib(n) = fib(n-1) + fib(n-2)

So the sequence looks like:

0, 1, 1, 2, 3, 5, 8, 13, ...
[Link](6)

 n = 6 → not <= 1 → go to recursion


 fib(6) = fib(5) + fib(4)

2 . fib(5)

 n = 5 → not <= 1 → recursion


 fib(5) = fib(4) + fib(3)

[Link](4)

 n = 4 → not <= 1 → recursion


 fib(4) = fib(3) + fib(2)

goes on

Base Cases

 fib(1) = 1
 fib(0) = 0
 fib(2) = 1 + 0 = 1
 fib(3) = fib(2) + fib(1) = 1 + 1 = 2
 fib(4) = fib(3) + fib(2) = 2 + 1 = 3
 fib(5) = fib(4) + fib(3) = 3 + 2 = 5
 fib(6) = fib(5) + fib(4) = 5 + 3 = 8

21
Example 3: Sum of first n natural numbers
def sum_n(n):
if n == 0:
return 0
return n + sum_n(n-1)

print(sum_n(5)) # Output: 15
Explanation:

 sum_n(1) = 1 + 0 = 1
 sum_n(2) = 2 + 1 = 3
 sum_n(3) = 3 + 3 = 6
 sum_n(4) = 4 + 6 = 10
 sum_n(5) = 5 + 10 = 15

Variable Scope: Local, Global and Nonlocal


Scope determines where a variable can be accessed. Python follows the LEGB rule
(Local, Enclosing, Global, Built-in).

Local Variables

Local variables are defined inside a function and accessible only within that function.

def func_local():
x = 10 # local
print('Inside:', x)

func_local() # Output: Inside: 10


# print(x) # Would cause NameError: x is not defined
Explanation: x exists only during func_local execution.

Global Variables

 Global variables are defined at module level and accessible in functions for reading. To
modify them inside functions, use 'global' keyword.

x = 5 # global
def read_global():

22
print('Read global:', x)
read_global() # Output: Read global: 5
def modify_global():
global x
x = 20

modify_global()

print('After modify:', x) # Output: After modify: 20


Explanation: Without 'global' assignment inside function would create a new local variable.
Nonlocal Variables (Enclosing scope)

 nonlocal is used in nested functions to modify a variable in the enclosing (but non-
global) scope.

def outer():
msg = 'outer'
print(“before msg value”,msg)
def inner():
nonlocal msg
msg = 'changed by inner'
inner()
print(“after msg value”, msg)
outer() # Output: changed by inner
Explanation: nonlocal allows inner to rebind the variable defined in outer's scope.

Python Built-in Methods

Math (the math module)

The math module contains functions for mathematical operations that go beyond Python's
basic arithmetic (+, -, *, /). You must import it (import math) before use.

Key functions & constants

 [Link](x) — square root of x (float)


 [Link](x, y) — x**y, returns float
 [Link](n) — factorial of non-negative integer n

23
 [Link](x) — largest integer ≤ x
 [Link](x) — smallest integer ≥ x
 [Link](x), [Link](x) — trigonometric functions (input in radians)
 [Link], math.e — mathematical constants

Examples
import math

# 1. Square root
print([Link](36)) # 6.0

# 2. Power
print([Link](2, 3)) # 8.0

# 3. Factorial
print([Link](5)) # 120

# 4. Floor and ceil

print([Link](3.7)) # 3 # Returns the largest integer that is less than


or equal to the given number.

print([Link](3.2)) # 4 #Returns the smallest integer that is greater than or equal to the
given number.

# 5. Using pi
circumference = 2 * [Link] * 5 # circle radius 5
print(circumference)

Short exercise

Calculate the area of a circle with radius input by the user (use [Link]).

String Built-in Methods

What strings are ?

Strings are immutable sequences of characters. The string type has many built-in methods for
inspecting and transforming text.

24
Very useful methods

 .strip(), .lstrip(), .rstrip() — remove whitespace


 .lower(), .upper(), .title() — change case
 .split(sep) — split into list using sep (default whitespace)
 .join(iterable) — join strings with a separator
 .replace(old, new[, count]) — replace substrings
 .find(sub) / .index(sub) — find substring (index or -1/exception)
 .startswith(prefix) / .endswith(suffix) — boolean checks

Examples

STRIP ()

 strip() → removes whitespace from both sides


 lstrip() → removes whitespace from the left
 rstrip() → removes whitespace from the right

Examples:

s = " Hello Python "


print([Link]()) # "Hello Python"
print([Link]()) # "Hello Python "
print([Link]()) # " Hello Python

CHANGE CASE

 lower() → convert to lowercase


 upper() → convert to uppercase
 title() → capitalize each word (title case)

Examples:
text = "hello python students"

print([Link]()) # "hello python students"


print([Link]()) # "HELLO PYTHON STUDENTS"
print([Link]())

25
split(sep) — Split into List :

What it does:

Breaks a string into parts and returns a list.

 If you don’t give a separator → splits on spaces


 If you give a separator → splits using that character

Examples:
text = "apple,banana,grapes"

print([Link](","))
# ['apple', 'banana', 'grapes']

print("Python is fun".split())
# ['Python', 'is', 'fun']

join(iterable) — Join Strings With a Separator


What it does:

Used to join a list of strings into a single string.

Example:
words = ["Python", "is", "fun"]

print(" ".join(words)) # "Python is fun"


print("-".join(words)) # "Python-is-fun"

replace(old, new[, count]) — Replace Substrings


What it does:

Replaces parts of a string.


Optional count limits how many replacements to make.

Examples:
text = "I love Python. Python is great."

print([Link]("Python", "Java"))
# "I love Java. Java is great."

26
print([Link]("Python", "Java", 1))
# "I love Java. Python is great."

find(sub) / index(sub) — Search for Substring


Difference:

 find() → returns index OR -1 if not found


 index() → returns index OR error if not found

Examples:
text = "Hello Python"

print([Link]("Python")) # 6
print([Link]("Java")) # -1

print([Link]("Hello")) # 0
# print([Link]("Java")) # error

startswith(prefix) / endswith(suffix)
What they do:

Check if a string begins or ends with a value.

Examples:
filename = "[Link]"

print([Link]("no")) # True
print([Link](".pdf")) # True
print([Link](".txt")) # False

Short exercise

Given a CSV-style string: 'id,name,score', split it into fields and print them nicely.

27
Date & Time (datetime module)

What it is ?

The datetime module provides classes for manipulating dates and times: date, time, datetime,
and timedelta.

Common operations

 [Link]() — current local date & time


 [Link]() — today's date
 [Link](string, fmt) — parse string to datetime
 [Link](fmt) — format datetime to string
 timedelta(days=…, hours=…) — duration to add/subtract

Examples
from datetime import datetime, date, timedelta

# 1. now and today


print([Link]())
print([Link]())

# 2. format date
now = [Link]()
print([Link]("%d-%m-%Y %H:%M"))

# 3. parse string to datetime


dt = [Link]("2025-12-11 15:30", "%Y-%m-%d %H:%M")
print(dt, type(dt))

# 4. add days
print([Link]() + timedelta(days=7))

# 5. difference between dates


d1 = date(2025, 1, 1)
d2 = date(2025, 12, 31)
print(d2 - d1) # timedelta object

Symbol Meaning Example


%d Day (01–31) 02
%D Date (MM/DD/YY) 12/16/25
%m Month (01–12) 12
%M Minute (00–59) 30

28
Symbol Meaning Example
%Y Year (4-digit) 2025
%y Year (2-digit) 25

Short exercise

Ask user for a date in dd-mm-yyyy format and print the weekday for that date.

PDF Extraction (third-party libraries)

Note: PDF extraction is not part of Python core. Popular third-party libraries include PyPDF2,
pdfplumber, and fitz (from PyMuPDF). These are installed with pip install PyPDF2 pdfplumber
PyMuPDF.

The Purpose of PDF Extraction :

The purpose of PDF extraction using third-party libraries is to convert static PDF documents into
structured, machine-readable data for automation, analysis, and reuse.

What you can do

 Open and read PDF metadata


 Count pages
 Extract text from pages (varies by PDF complexity)
 Extract images and tables (pdfplumber and PyMuPDF are better)

Why third-party libraries are needed ?

Native programming languages usually cannot interpret PDFs well because:

 PDFs don’t store content in reading order


 Text may be positioned visually, not logically
 Fonts, encodings, and layouts vary widely

Third-party libraries handle:

 PDF parsing
 Text decoding
 Layout analysis
 Table detection
 OCR (for scanned PDFs) – OCR stands for Optical Character Recognition.

29
Example with PyPDF2 (text extraction)

Working with PDF using PyPDF2

1. Install PyPDF2 in VS Code terminal:

pip install PyPDF2

2. Put a PDF file [Link] in the same folder.


3. In [Link], write:

import PyPDF2

with open('[Link]', 'rb') as f:


reader = [Link](f)
print("Pages:", len([Link]))
print([Link][0].extract_text()[:200]) # first 200 characters

Explanation:

 rb → read binary mode for PDF.


 len([Link]) → counts pages.
 extract_text() → gets text from the page.

Example with pdfplumber (better for tables)


import pdfplumber

with [Link]('[Link]') as pdf:


page = [Link][0]
text = page.extract_text()
tables = page.extract_tables()
print(text)
print(tables) # list of tables, each a list of rows

Short exercise

Use PyPDF2 to count pages of a sample PDF and print the first 200 characters of page 1.

30
CSV (csv module)

What it is?

CSV (comma-separated values) files store tabular data. Python's built-in csv module
reads/writes CSVs safely (handling quoting, commas inside fields, etc.).

Common patterns

 [Link](f) — iterate rows as lists


 [Link](f) — write rows from lists
 [Link](f) / [Link](f) — read/write rows as dictionaries

Examples
import csv

# 1. Write CSV
with open('[Link]', 'w', newline='') as f:
writer = [Link](f)
[Link](['id', 'name', 'score'])
[Link]([1, 'Alice', 85])
[Link]([2, 'Bob', 92])

# 2. Read CSV
with open('[Link]', 'r') as f:
reader = [Link](f)
for row in reader:
print(row)

# 3. DictReader
with open('[Link]', 'r') as f:
reader = [Link](f)
for row in reader:
print(row['name'], row['score'])

# 4. DictWriter
with open('[Link]', 'w', newline='') as f:
fieldnames = ['id', 'name', 'score']
writer = [Link](f, fieldnames=fieldnames)
[Link]()
[Link]({'id': 3, 'name': 'Carl', 'score': 78})

31
Working with CSV

1. In [Link], write:

import csv
# Write CSV file
with open('[Link]', 'w', newline='') as f:
writer = [Link](f)
[Link](['id', 'name', 'score'])
[Link]([1, 'Alice', 85])
[Link]([2, 'Bob', 90])

# Read CSV file


with open('[Link]', 'r') as f:
reader = [Link](f)
for row in reader:
print(row)

Explanation:

 [Link] is like an Excel table.


 [Link]() writes a row.
 [Link]() reads rows.

After running, you will see:

['id', 'name', 'score']


['1', 'Alice', '85']
['2', 'Bob', '90']

Short exercise

Read a CSV of students and compute the average score.

OPERATORS IN PYTHON

1. Operators in Python

Operators are symbols used to perform operations on values or variables.

32
1.1 Arithmetic Operators

Used for mathematical calculations.

Operator Meaning
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus

Examples:

a = 10
b=3
print(a + b) # 13
print(a - b) # 7
print(a * b) # 30
print(a / b) # 3.33
print(a % b) # 1

1.2 Relational (Comparison) Operators

Used to compare values. Result is True or False.

Operator Meaning
> Greater than
< Less than
== Equal to
!= Not equal
>= Greater or equal

Examples:

x=5
y = 10
print(x > y)
print(x < y)
print(x == 5)
print(x != y)

33
print(y >= 10)

1.3 Logical Operators

Used to combine conditions.

Operator Meaning
and Both conditions true
or Any one condition true
not Reverse result

Examples:

a = 10
b = 20
print(a > 5 and b > 15)
print(a > 15 or b > 15)
print(not(a > 5))

2. Conditional Statements

Used to make decisions based on conditions.

2.1 if statement

age = 18
if age >= 18:
print("Eligible to vote")
else:
print(“not eligible”)
num = 5
if num > 0:
print("Positive number")

2.2 if–else statement

num = 10
if num % 2 == 0:
print("Even")
else:

34
print("Odd")
marks = 35
if marks >= 40:
print("Pass")
else:
print("Fail")

2.3 if–elif–else statement

marks = 75
if marks >= 90:
print("Grade A")
elif marks >= 60:
print("Grade B")
else:
print("Grade C")

3. Looping Statements

Loops are used to repeat a block of code.

3.1 for loop

for i in range(5):
print(i)
for ch in "Python":
print(ch)

3.2 while loop

i=1
while i <= 5:
print(i)
i =i+1 // i+=1
count = 3
while count > 0:
print("Countdown:", count)
count -= 1

4. break and continue

35
4.1 break statement

Used to stop the loop immediately.

for i in range(1, 6):


if i == 4:
break
print(i)
while True:
print("Hello")
break

4.2 continue statement

Used to skip current iteration.

for i in range(1, 6):


if i == 3:
continue
print(i)
for i in range(5):
if i % 2 == 0:
continue
print(i)

Modules

What a module is ?

A module is simply a .py file containing functions, classes, or variables. Use import
module_name to use it.

How to structure and use

 Create ([Link]) file name with functions.


 In another file use import mymath or from mymath import add, sub.
 Use if __name__ == '__main__': to make a file runnable and import-safe.

Example module [Link]


# [Link]
def add(a, b):

36
return a + b

if __name__ == '__main__': # code inside executes


print('Test add:', add(2,3))

#another file Importing and using


import mymath
print([Link](4,5))

from mymath import add


print(add(1,2))

Using your own module

1. Create a new file [Link] in the same folder:

# [Link]
def add(a, b):
return a + b

def sub(a, b):


return a - b

2. In [Link], use it:

import mymath

print([Link](5, 3)) # Output: 8


print([Link](10, 4)) # Output: 6

2. Python Packages

A Package is a directory (folder) that contains multiple modules. To make Python treat a folder
as a package, it must contain a file named __init__.py (this file can be empty).

Step-by-Step Package Creation

1. Create a folder named University.


2. Inside University, create an empty file: __init__.py.

37
3. Create a module inside University named [Link]:

# [Link]
def get_info(name, branch):
return f"Student: {name}, Branch: {branch}"
Importing from a Package

 Static Example:

from University import student


print(student.get_info("Alice", "CS"))

 Dynamic Example:

from [Link] import get_info


name = input("Enter student name: ")
dept = input("Enter department: ")
print(get_info(name, dept))

3. Built-in Modules (Examples)

Python comes with a "standard library" of pre-made modules.

The math Module


import math
print([Link](64)) # Output: 8.0
print([Link]) # Output: 3.1415...
The random Module
import random
# Dynamic use: generating a random OTP
print("Your OTP is:", [Link](1000, 9999))

PYTHON FILE OPERATIONS :

What is a File?

A file is a place where data is stored permanently on a computer.

Examples:

38
 .txt → text file
 .csv → table data
 .log → logs
 .json → structured data

Why file operations are needed?

 To save data permanently


 To read saved data later
 To update or delete data

File Operations in Python

Python allows us to:

1. Create a file
2. Open a file
3. Read a file
4. Write to a file
5. Append to a file
6. Close a file

Opening a File in Python

Syntax
file_object = open("filename", "mode")
Example
f = open("[Link]", "r")

Creating and Writing to a File (w mode)

Example 1: Create & Write


f = open("[Link]", "w")
[Link]("Name: Ravi\n")
[Link]("Age: 20\n")
[Link]()

Write Multiple Lines


f = open("[Link]", "w")
[Link]("Maths: 85\n")
[Link]("Science: 90\n")
[Link]("English: 88\n")
[Link]()
39
Writing Files

a) write()

The write() function writes a single string to a file.

f = open("[Link]", "w")
[Link]("Welcome to Python")
[Link]()

 Existing data will be erased in w mode.

b) writelines()

The writelines() function writes multiple strings to a file.

f = open("[Link]", "w")
[Link](["Hello\n", "Python\n", "File Handling"])
[Link]()

Newline (\n) must be added manually.

-------------------------------------------------------------------------------------------------------------------------------

Reading Files

a) read()

Reads the entire content of the file.

f = open("[Link]", "r")
content = [Link]()
print(content)
[Link]()

40
b) readline()

Reads one line at a time.

f = open("[Link]", "r")
print([Link]())
print([Link]())
[Link]()

c) readlines()

Reads all lines and returns them as a list.

f = open("[Link]", "r")
lines = [Link]()
print(lines)
[Link]()

-------------------------------------------------------------------------------------------------------------------------------

Closing Files – close()

The close() function releases system resources and saves changes.

[Link]()

Always close a file after use.

-------------------------------------------------------------------------------------------------------------------------------

Manipulating File Pointer

The file pointer shows the current position in the file.

a) tell()

Returns the current position of the pointer.

f = open("[Link]", "r")
print([Link]())
[Link]()

41
b) seek()

Moves the pointer to a specific position.

f = open("[Link]", "r")
[Link](0)
print([Link]())
[Link]()

Appending Data (a mode)

Appending adds data without deleting old data

Example 1: Append Data


f = open("[Link]", "a")
[Link]("Course: Python\n")
[Link]()

Example 2: Append Multiple Entries


f = open("[Link]", "a")
[Link]("User logged in\n")
[Link]("User logged out\n")
[Link]()

Using with Statement (BEST PRACTICE)

 Automatically closes file


 Safer and cleaner

Example 1: Write using with


with open("[Link]", "w") as f:
[Link]("Hello Python")

Example 2: Read using with


with open("[Link]", "r") as f:
print([Link]())

Checking File Exists (Using os module)

42
 os → Operating System
 [Link] → Path-related utilities provided by the Operating System interface
 [Link]() → Checks whether a file or directory exists at a given path

import os

if [Link]("[Link]"):
print("File exists")
else:
print("File not found")

Deleting a File

import os
[Link]("[Link]")

Reading File Using Loop

Example
f = open("[Link]", "r")

for line in f:
print(line)

[Link]()

Mode Meaning
r Read
w Write (creates new file / deletes old content)
a Append (adds data at end)
x Create new file
r+ Read + Write
w+ Write + Read
a+ Append + Read

-------------------------------------------------------------------------------------------------------------------------------

43
📂 Directory Operations in Operating Systems

1. What is a Directory?

 A directory (also called a folder) is a container used to organize files and other
directories.
 Directories help structure the file system into a hierarchy, making it easier to manage
data.
 Example: In Windows, you might have C:\Users\Documents; in Linux/macOS,
/home/user/Documents.
 Example : C:/Users/Student/Documents

Current Working Directory (CWD)

 The current working directory is the folder your shell or terminal is currently "pointing
to."
 All commands you run will apply to this directory unless you specify another path.
 Commands:
o Linux/macOS: pwd (print working directory)
o Windows CMD: cd (without arguments shows current directory

Get Current Working Directory


import os
print([Link]())

Changing Directory

 Used to move from one directory to another.


 Commands:
o Linux/macOS: cd directory_name
o Windows: cd directory_name
 Example:
o cd Documents → moves into the Documents folder.
o cd .. → moves one level up (to the parent directory).

Changing Directory

The chdir() function is used to change the current working directory.

Syntax
[Link]("path")
Example
[Link]("D:/Python")
print([Link]())

44
Listing Directory Contents

 Shows files and subdirectories inside the current directory.


 Commands:
o Linux/macOS: ls
o Windows: dir
 Options:
o ls -l → detailed list with permissions, size, and date.
o ls -a → includes hidden files.

Listing Directory Contents

The listdir() function displays all files and folders in a directory.

Example
print([Link]())
List Specific Directory
print([Link]("D:/Python"))

-------------------------------------------------------------------------------------------------------------------------------

Making a New Directory

 Creates a new folder.


 Commands:
o Linux/macOS: mkdir new_folder
o Windows: mkdir new_folder
 Example: mkdir projects → creates a folder named projects.

a) mkdir() – Create one directory


[Link]("NewFolder")
b) makedirs() – Create nested directories
[Link]("MainFolder/SubFolder")

-------------------------------------------------------------------------------------------------------------------------------

Renaming a Directory

 Changes the name of an existing folder.


 Commands:
o Linux/macOS: mv old_name new_name
o Windows: rename old_name new_name

45
 Example: mv reports old_reports → renames reports to old_reports
 The rename() function is used to rename files or folders.

 Example (Directory)
 [Link]("OldFolder", "NewFolder")

 Example (File)
 [Link]("[Link]", "[Link]")

Removing a Directory or File

 Deletes files or folders.


 Commands:
o Linux/macOS:
 File: rm [Link]
 Empty directory: rmdir folder_name
 Directory with contents: rm -r folder_name
o Windows:
 File: del [Link]
 Directory: rmdir /S folder_name (asks for confirmation)
 ⚠️ Warning: These actions are permanent unless you use a recycle bin or trash system.

-------------------------------------------------------------------------------------------------------------------------------

Removing a Directory or File

a) Remove a File – remove()


[Link]("[Link]")

b) Remove an Empty Directory – rmdir()


[Link]("NewFolder")

 Directory must be empty.

c) Remove Directory with Files – [Link]()


import shutil
[Link]("MainFolder")

 Deletes folder and all its contents.

46
-------------------------------------------------------------------------------------------------------------------------------

Checking File or Directory Exists

if [Link]("[Link]"):
print("Exists")
else:
print("Not Found")

Exception Handling :

Exception handling is a mechanism that allows programs to deal with unexpected events or
errors gracefully, instead of crashing. Python uses the try, except, else, and finally blocks to
manage exceptions

try Block

 Code that might raise an exception is placed inside a try block.


 If an error occurs, Python immediately jumps to the corresponding except block.

try:
x = 10 / 0

except Block

 Handles the error that occurred in the try block.


 You can catch specific exceptions or use a general one.

try:
x = 10 / 0
except ZeroDivisionError:
print("You cannot divide by zero!")
-------------------------------------------------------------------------------------------------------------------------------

 ValueError

Occurs when a function receives the right type but an invalid value.

try:
num = int("abc") # invalid string for int conversion
except ValueError:
print("Caught a ValueError: invalid input!")

47
-------------------------------------------------------------------------------------------------------------------------------

 TypeError

Raised when an operation is applied to an object of inappropriate type.

try:
result = "hello" + 5 # cannot add str and int
except TypeError:
print("Caught a TypeError: wrong type used!")

 IndexError

Raised when accessing a list index that doesn’t exist.

try:
nums = [1, 2, 3]
print(nums[5]) # out of range
except IndexError:
print("Caught an IndexError: index out of range!")

-------------------------------------------------------------------------------------------------------------------------------

 KeyError

Raised when accessing a dictionary key that doesn’t exist.

try:
data = {"a": 1}
print(data["b"]) # key not found
except KeyError:
print("Caught a KeyError: key not found!")
-------------------------------------------------------------------------------------------------------------------------------

 FileNotFoundError

Raised when trying to open a file that doesn’t exist.

try:
f = open("[Link]")
except FileNotFoundError:
print("Caught a FileNotFoundError: file not found!")

48
-------------------------------------------------------------------------------------------------------------------------------

 AttributeError

Raised when trying to access an attribute/method that doesn’t exist.

try:
text = "hello"
[Link]("!") # strings don’t have append()
except AttributeError:
print("Caught an AttributeError: invalid attribute!")

ImportError / ModuleNotFoundError

Raised when importing a module that doesn’t exist.

try:

import non_existing_module

except ImportError:
print("Caught an ImportError: module not found!")
-------------------------------------------------------------------------------------------------------------------------------

 else Block

 Runs only if no exception occurs in the try block.


 Good for code that should execute when everything goes smoothly.

try:
num = int("10")
except ValueError:
print("Conversion failed.")
else:
print("Conversion successful:", num)

-------------------------------------------------------------------------------------------------------------------------------

 finally Block

 Runs no matter what happens (whether an exception occurs or not).


 Often used for cleanup tasks like closing files or releasing resources.

49
try:
f = open("[Link]", "r")
content = [Link]()
except FileNotFoundError:
print("File not found.")
finally:
print("Closing file...")
[Link]() # executed whether error occurs or not

 Custom Exceptions

 You can define your own exceptions by creating a class that inherits from Exception.
 Useful when you want to enforce specific rules in your program.

class NegativeNumberError(Exception):
pass

def check_number(n):
if n < 0:
raise NegativeNumberError("Negative numbers are not allowed!")
else:
print("Valid number:", n)

try:
check_number(-5)
except NegativeNumberError as e:
print("Error:", e)
-------------------------------------------------------------------------------------------------------------------------------

Example: Age Validation with Custom Exception

Suppose you want to enforce that a person’s age must be at least 18 to register for a service.

# Define a custom exception


class UnderAgeError(Exception):
def __init__(self, age):
super().__init__(f"Age {age} is too young. Must be 18 or older.")
[Link] = age

# Function that uses the custom exception


def register_user(age):

50
if age < 18:
raise UnderAgeError(age)
else:
print("Registration successful!")

# Using try-except to handle it


try:
register_user(15)
except UnderAgeError as e:
print("Error:", e)

Error vs Exception

Aspect Error Exception

Occurs At compile-time or runtime At runtime

Can be handled? Usually not (fatal) Yes, with try-except

Example SyntaxError, MemoryError ValueError, ZeroDivisionError

 Error: Problems that often cannot be handled (e.g., syntax errors stop the program
before running).
 Exception: Problems that occur during execution and can be caught with try-except

-------------------------------------------------------------------------------------------------------------------------------

OOPS CONCEPTS :

 Object-Oriented Programming System (OOPS) in Python


 Object-Oriented → Programs are built using objects (real-world entities like Car,
Student, BankAccount).
 Programming System → It’s a structured way of writing code that makes it reusable,
modular, and easier to maintain.

Why OOPS is Important

 Makes code modular (split into parts).


 Encourages reusability (inheritance).
 Improves security (encapsulation).
 Provides flexibility (polymorphism).
 Helps model real-world problems naturally (objects like Car, Bank, Student).

51
Detailed Explanations of OOP Concepts

1. Class and Objects

 Class: Think of it as a blueprint. It defines what attributes (data) and methods


(functions) an object will have.
 Object: A real-world instance created from the class. Each object can hold different
values but follows the same structure.

# Example 1: Simple class

class Car:

def __init__(self, brand, model):

[Link] = brand

[Link] = model

car1 = Car("Toyota", "Corolla")

print([Link], [Link]) # Toyota Corolla

# Example 2: Methods in class

class Dog:

def __init__(self, name):

[Link] = name

def bark(self):

return f"{[Link]} says Woof!"

dog1 = Dog("Buddy")

print([Link]()) # Buddy says Woof!

# Example 3: Multiple objects

52
class Student:

def __init__(self, name, grade):

[Link] = name

[Link] = grade

s1 = Student("Alice", "A")

s2 = Student("Bob", "B")

print([Link], [Link]) # Alice Bob

2. Inheritance

 Allows a child class to reuse and extend the functionality of a parent class.
 Promotes code reusability and avoids duplication.
 Types:
o Single inheritance → One parent, one child.
o Multi-level inheritance → Child becomes parent of another child.
o Multiple inheritance → Child inherits from multiple parents.

# Example 1: Single inheritance

class Animal:

def speak(self):

return "Animal speaks"

class Dog(Animal):

def speak(self):

return "Dog barks"

d = Dog()

print([Link]()) # Dog barks

# Example 2: Multi-level inheritance

class Vehicle:

53
def move(self):

return "Vehicle moves"

class Car(Vehicle):

def move(self):

return "Car drives"

class SportsCar(Car):

def move(self):

return "SportsCar zooms"

sc = SportsCar()

print([Link]()) # SportsCar zooms

# Example 3: Multiple inheritance

class Father:

def skills(self):

return "Gardening"

class Mother:

def skills(self):

return "Cooking"

class Child(Father, Mother):

def skills(self):

return f"{[Link](self)} & {[Link](self)}"

c = Child()

print([Link]()) # Gardening & Cooking

[Link]

54
 Hiding internal details of a class and controlling access.
 Achieved using:
o Public attributes → accessible everywhere.
o Protected attributes (_var) → accessible within class and subclasses.
o Private attributes (__var) → accessible only inside the class.
 Ensures data security and prevents accidental modification.

Example: A BankAccount hides its balance (__balance) and only allows deposits/withdrawals
through methods.

# Example 1: Private variable

class BankAccount:

def __init__(self, balance):

self.__balance = balance # private

def deposit(self, amount):

self.__balance += amount

def get_balance(self):

return self.__balance

acc = BankAccount(1000)

[Link](500)

print(acc.get_balance()) # 1500

# Example 2: Protected variable

class Employee:

def __init__(self, name, salary):

self._salary = salary # protected

[Link] = name

e = Employee("John", 5000)

print(e._salary) # Accessible but discouraged

55
# Example 3: Encapsulation with getter/setter

class Student:

def __init__(self, name):

self.__name = name

def get_name(self):

return self.__name

def set_name(self, new_name):

self.__name = new_name

s = Student("Alice")

print(s.get_name()) # Alice

s.set_name("Bob")

print(s.get_name()) # Bob

[Link]

 Means “many forms”.


 Same method name behaves differently depending on the object.
 Two types:
o Compile-time (overloading) → Same method name, different parameters
(Python simulates this).
o Run-time (overriding) → Child class redefines parent method.

# Example 1: Method overriding

class Bird:

def sound(self):

return "Chirp"

class Dog:

56
def sound(self):

return "Bark"

for animal in [Bird(), Dog()]:

print([Link]()) # Chirp, Bark

# Example 2: Built-in polymorphism

print(len("Hello")) # 5

print(len([1,2,3])) # 3

# Example 3: Operator overloading

print(10 + 20) # 30

print("Hello" + "World") # HelloWorld

5. Data Abstraction

 Hiding implementation details and exposing only the necessary interface.


 Achieved using abstract classes (abc module).
 Forces subclasses to implement certain methods.

from abc import ABC, abstractmethod

# Example 1: Abstract class

class Shape(ABC):

@abstractmethod

def area(self):

pass

class Circle(Shape):

def __init__(self, r):

self.r = r

def area(self):

57
return 3.14 * self.r * self.r

c = Circle(5)

print([Link]()) # 78.5

# Example 2: Multiple abstract methods

class Vehicle(ABC):

@abstractmethod

def start(self): pass

@abstractmethod

def stop(self): pass

class Car(Vehicle):

def start(self): return "Car started"

def stop(self): return "Car stopped"

car = Car()

print([Link](), [Link]())

# Example 3: Abstract + concrete methods

class Animal(ABC):

@abstractmethod

def sound(self): pass

def sleep(self):

return "Sleeping..."

class Dog(Animal):

def sound(self): return "Bark"

d = Dog()

58
print([Link](), [Link]()) # Bark Sleeping...

6. Overloading

 Python doesn’t support traditional overloading like Java/C++.


 But we can simulate it using:
o Default arguments
o Variable-length arguments (*args)
o Operator overloading (__add__, __str__, etc.)

# Example 1: Function with default arguments

def add(a, b=0, c=0):

return a + b + c

print(add(5)) #5

print(add(5, 10)) # 15

print(add(5, 10, 20)) # 35

# Example 2: Operator overloading

class Book:

def __init__(self, pages):

[Link] = pages

def __add__(self, other):

return [Link] + [Link]

b1 = Book(100)

b2 = Book(200)

print(b1 + b2) # 300

# Example 3: Method overloading using *args

class Calculator:

def add(self, *args):

59
return sum(args)

c = Calculator()

print([Link](2,3)) #5

print([Link](2,3,4,5)) # 14

7. Overriding (Dynamic Polymorphism)

 Child class redefines a method from the parent class.


 At runtime, Python decides which method to call depending on the object type.
 Often used with super() to call parent’s version too

# Example 1: Simple overriding

class Parent:

def greet(self):

return "Hello from Parent"

class Child(Parent):

def greet(self):

return "Hello from Child"

c = Child()

print([Link]()) # Hello from Child

# Example 2: Using super()

class Animal:

def sound(self):

return "Some sound"

60
class Dog(Animal):

def sound(self):

return super().sound() + " + Bark"

d = Dog()

print([Link]()) # Some sound + Bark

# Example 3: Dynamic method call

class Shape:

def area(self):

return "Undefined"

class Square(Shape):

def __init__(self, side):

[Link] = side

def area(self):

return [Link] * [Link]

shapes = [Shape(), Square(4)]

for s in shapes:

print([Link]()) # Undefined, 16

-------------------------------------------------------------------------------------------------------------------------------

Multithreading

What is Multithreading?

Multithreading is a programming technique that allows a program to execute multiple tasks


(threads) at the same time within a single process.

 A thread is the smallest unit of execution


 Threads share the same memory space

61
 Improves performance for I/O-bound tasks

1. Understanding Threads

What is a Thread?

A thread is a lightweight sub-process that runs independently but shares resources of the
parent process.

Key Points

 Faster than processes


 Shares memory
 Used for parallel tasks

# Example 1: Creating a simple thread

import threading

def print_numbers():

for i in range(5):

print("Number:", i)

t = [Link](target=print_numbers)

[Link]()

[Link]() # wait for thread to finish

print("Main thread finished")

# Example 2: Multiple threads

def worker(name):

print(f"Worker {name} is running")

threads = []

for i in range(3):

62
t = [Link](target=worker, args=(i,))

[Link](t)

[Link]()

for t in threads:

[Link]()

# Example 3: Thread with delay

import time

def delayed_task():

[Link](2)

print("Task completed after delay")

t = [Link](target=delayed_task)

[Link]()

print("Main thread continues...")

[Link]()

2. Forking Threads (Creating Multiple Threads)

Definition

Forking threads means creating and running multiple threads to perform tasks concurrently.

Methods to create threads

1. Using Thread class


2. Extending Thread class

# Example 1: Forking multiple threads

import threading

63
def task(name):

print(f"Task {name} started")

for i in range(3):

t = [Link](target=task, args=(i,))

[Link]()

# Example 2: Forking with different functions

def task1():

print("Task 1 running")

def task2():

print("Task 2 running")

t1 = [Link](target=task1)

t2 = [Link](target=task2)

[Link]()

[Link]()

[Link]()

[Link]()

# Example 3: Forking threads with loops

def count_up(name):

for i in range(3):

print(f"{name} counting {i}")

threads = [[Link](target=count_up, args=(f"Thread-{i}",)) for i in range(2)]

for t in threads:

64
[Link]()

for t in threads:

[Link]()

[Link] Threads

Definition

Thread synchronization ensures that only one thread accesses a shared resource at a time,
preventing data inconsistency.

Problem without synchronization

 Race condition
 Incorrect output

Solution

 Locks (Lock)
 Semaphores

# Example 1: Using Lock

import threading

lock = [Link]()

shared_counter = 0

def increment():

global shared_counter

for _ in range(1000):

[Link]()

shared_counter += 1

65
[Link]()

threads = [[Link](target=increment) for _ in range(5)]

for t in threads: [Link]()

for t in threads: [Link]()

print("Final counter:", shared_counter)

# Example 2: Synchronizing with RLock

lock = [Link]()

def safe_print(msg):

with lock:

print(msg)

t1 = [Link](target=safe_print, args=("Thread 1 printing",))

t2 = [Link](target=safe_print, args=("Thread 2 printing",))

[Link](); [Link]()

[Link](); [Link]()

# Example 3: Synchronizing with Semaphore

semaphore = [Link](2) # allow 2 threads at a time

def limited_task(name):

with semaphore:

print(f"{name} is running")

import time; [Link](1)

threads = [[Link](target=limited_task, args=(f"Thread-{i}",)) for i in range(5)]

for t in threads: [Link]()

for t in threads: [Link]()

66
-------------------------------------------------------------------------------------------------------------------------------

Python Database Connectivity

What is Database Connectivity?

Database connectivity is the process of connecting a Python program to a database to store,


retrieve, update, and delete data.

Python supports many databases such as:

 MySQL (Relational Database – SQL)


 MongoDB (NoSQL Database)

Python + MySQL Database Connectivity

What is MySQL?

MySQL is a relational database that stores data in tables (rows and columns) and uses SQL
queries.

Step 1: Install Required Package

pip install mysql-connector-python

Step 2: Import Connector

import [Link]

Step 3: Establish Database Connection

conn = [Link](
host="localhost",
user="root",
password="password",
database="student_db"
)

67
print("Database connected")
Explanation

 host → Database server


 user → MySQL username
 password → MySQL password
 database → Database name

Step 4: Create Cursor Object

A cursor is used to execute SQL queries.

cursor = [Link]()
-------------------------------------------------------------------------------------------------------------------------------
CRUD Operations in MySQL using Python

C → CREATE (Insert Data)

Example 1: Insert single record

sql = "INSERT INTO students (id, name, age) VALUES (%s, %s, %s)"
values = (1, "Priya", 21)

[Link](sql, values)
[Link]()

print("Record inserted")

Example 2: Insert multiple records


sql = "INSERT INTO students VALUES (%s, %s, %s)"
data = [
(2, "Anu", 22),
(3, "Ram", 20)
]

[Link](sql, data)
[Link]()

Example 3: Insert without variables

[Link](
"INSERT INTO students VALUES (4, 'Kumar', 23)"

68
)
[Link]()

R → READ (Select Data)

Example 1: Fetch all records

[Link]("SELECT * FROM students")


result = [Link]()

for row in result:


print(row)

Example 2: Fetch one record

[Link]("SELECT * FROM students WHERE id=1")


print([Link]())

Example 3: Fetch specific columns

[Link]("SELECT name, age FROM students")


for row in cursor:
print(row)
-------------------------------------------------------------------------------------------------------------------------------

U → UPDATE (Modify Data)

Example 1: Update age

[Link](
"UPDATE students SET age=22 WHERE id=1"
)
[Link]()

Example 2: Update using variables

sql = "UPDATE students SET name=%s WHERE id=%s"


[Link](sql, ("Priya D", 1))
[Link]()

Example 3: Update multiple rows

[Link]("UPDATE students SET age=25")


[Link]()

69
-------------------------------------------------------------------------------------------------------------------------------

D → DELETE (Remove Data)

Example 1: Delete one record

[Link]("DELETE FROM students WHERE id=3")


[Link]()

Example 2: Delete using condition


[Link]("DELETE FROM students WHERE age > 22")
[Link]()

Example 3: Delete all records


[Link]("DELETE FROM students")
[Link]()

-------------------------------------------------------------------------------------------------------------------------------

Python + MongoDB Database Connectivity

What is MongoDB?

MongoDB is a NoSQL database that stores data as documents (JSON-like format).

Step 1: Install MongoDB Driver

pip install pymongo

Step 2: Import pymongo

import pymongo

Step 3: Connect to MongoDB

client = [Link]("mongodb://localhost:27017/")
db = client["student_db"]
collection = db["students"]

70
print("MongoDB connected")
Explanation

 client → MongoDB server


 db → Database
 collection → Table equivalent

CRUD Operations in MongoDB using Python

C → CREATE (Insert)
Example 1: Insert one document
collection.insert_one({
"id": 1,
"name": "Priya",
"age": 21
})
Example 2: Insert multiple documents
collection.insert_many([
{"id": 2, "name": "Anu", "age": 22},
{"id": 3, "name": "Ram", "age": 20}
])
Example 3: Insert without id
collection.insert_one({
"name": "Kumar",
"age": 23
})

R → READ (Find)
Example 1: Find all documents
for data in [Link]():
print(data)
Example 2: Find one document
print(collection.find_one({"id": 1}))
Example 3: Find specific field
for data in [Link]({}, {"name": 1}):
print(data)

71
U → UPDATE
Example 1: Update one document
collection.update_one(
{"id": 1},
{"$set": {"age": 22}}
)
Example 2: Update many documents
collection.update_many(
{"age": {"$gt": 21}},
{"$set": {"status": "Senior"}}
)
Example 3: Replace document
collection.replace_one(
{"id": 2},
{"id": 2, "name": "Anu", "age": 23}
)

D → DELETE
Example 1: Delete one document
collection.delete_one({"id": 3})
Example 2: Delete many documents
collection.delete_many({"age": {"$gt": 22}})
Example 3: Delete all documents
collection.delete_many({})

-------------------------------------------------------------------------------------------------------------------------------

MySQL vs MongoDB
Feature MySQL MongoDB

Type Relational NoSQL

Structure Tables Documents

Language SQL BSON

Schema Fixed Flexible

72
MySQL Queries
What is a Query?

A query is a command used to communicate with the database to create tables, insert data,
retrieve data, update data, or delete data.

MySQL uses SQL (Structured Query Language).

Types of MySQL Queries

1. DDL – Data Definition Language

(Used to define database structure)

CREATE Query

Creates a database or table.

CREATE DATABASE college;


CREATE TABLE students (
id INT,
name VARCHAR(50),
age INT
);

ALTER Query

Modifies table structure.

ALTER TABLE students ADD email VARCHAR(50);


ALTER TABLE students MODIFY age INT;
ALTER TABLE students DROP email;

DROP Query

Deletes a database or table permanently.

DROP TABLE students;


DROP DATABASE college;

73
TRUNCATE Query

Deletes all records but keeps table structure.

TRUNCATE TABLE students;

2. DML – Data Manipulation Language

(Used to manipulate data)

INSERT Query

Adds records to a table.

INSERT INTO students VALUES (1, 'Priya', 21);


INSERT INTO students (id, name) VALUES (2, 'Anu');
INSERT INTO students VALUES
(3, 'Ram', 20),
(4, 'Kumar', 22);

UPDATE Query

Updates existing records.

UPDATE students SET age = 22 WHERE id = 1;


UPDATE students SET name = 'Priya D' WHERE id = 1;
UPDATE students SET age = age + 1;

DELETE Query

Deletes records.

DELETE FROM students WHERE id = 3;


DELETE FROM students WHERE age > 21;
DELETE FROM students;

3. DQL – Data Query Language

(Used to retrieve data)

74
SELECT Query

Fetches data from a table.

SELECT * FROM students;


SELECT name, age FROM students;
SELECT * FROM students WHERE age = 21;

WHERE Clause

Filters records.

SELECT * FROM students WHERE age > 20;


SELECT * FROM students WHERE name = 'Priya';

ORDER BY

Sorts records.

SELECT * FROM students ORDER BY age;


SELECT * FROM students ORDER BY age DESC;

LIMIT

Restricts number of records.

SELECT * FROM students LIMIT 3;

4. Aggregate Functions

Function Description

COUNT() Total rows

SUM() Total value

AVG() Average

MIN() Minimum

75
Function Description

MAX() Maximum

SELECT COUNT(*) FROM students;


SELECT AVG(age) FROM students;
SELECT MAX(age) FROM students;

5. GROUP BY Clause

Groups rows with same values.

SELECT age, COUNT(*)


FROM students
GROUP BY age;

6. HAVING Clause

Used with GROUP BY.

SELECT age, COUNT(*)


FROM students
GROUP BY age
HAVING COUNT(*) > 1;

7. Joins in MySQL

INNER JOIN
SELECT [Link], [Link]
FROM students
INNER JOIN marks ON [Link] = [Link];
LEFT JOIN
SELECT [Link], [Link]
FROM students
LEFT JOIN marks ON [Link] = [Link];

8. Constraints (Important for Exams)

CREATE TABLE students (

76
id INT PRIMARY KEY,
name VARCHAR(50) NOT NULL,
age INT CHECK(age > 18)
);

9. Subqueries

SELECT * FROM students


WHERE age > (SELECT AVG(age) FROM students);

Python CGI

Writing Python Programs for CGI Applications

1. What is CGI?

CGI stands for Common Gateway Interface.

CGI is a standard interface that allows a web server to execute an external program (like a
Python script) and send the output back to the web browser.

Simple Definition (for students)

CGI is a way for a web server to run a program and show its output on a webpage.

2. Why CGI is Needed?

Static vs Dynamic Web Pages

 Static Web Page


o Same content for all users
o Example: HTML only
 Dynamic Web Page
o Content changes based on user input
o Example: Login form, registration form

👉 CGI helps create dynamic web pages

77
Diagram Representation

Browser

Web Server

Python CGI Script

HTML Output

Browser
-------------------------------------------------------------------------------------------------------------------------------

What is Python CGI?

Python CGI means using Python programs as CGI scripts to generate dynamic web content.

Python CGI programs:

 Run on the server


 Process user input
 Generate HTML output
 Can connect to databases

5. Why Python for CGI?

Explain to students:

 Easy syntax
 Readable code
 Beginner-friendly
 Powerful libraries
 Platform independent

6. Requirements for Python CGI

To run Python CGI programs, we need:

78
1. Web Server (Apache / IIS)
2. Python installed
3. CGI enabled in server
4. Python files stored in cgi-bin folder

Writing Python CGI Scripts

 Setup:
o Place scripts in the server’s cgi-bin directory.
o Make them executable (chmod 755 [Link]).
o Add a shebang line: #!/usr/bin/env python3.

Basic Example:

#!/usr/bin/env python3
print("Content-Type: text/html")
print() # Blank line after headers
print("<html><body><h1>Hello from Python CGI!</h1></body></html>")

4. Handling Input (Forms)

 Use Python’s cgi module to parse form data.


 Example with GET/POST:

#!/usr/bin/env python3
from cgi import FieldStorage
import html

print("Content-Type: text/html")
print()

form = FieldStorage()
name = [Link]("name", "Guest")
print(f"<p>Hello, {[Link](name)}!</p>")

Full Python CGI Program Example

This example shows a Student Management System with Create, Read, Update, Delete (CRUD)
operations using MySQL.

1. Setup

 Install MySQL connector:

79
pip install mysql-connector-python

 Configure Apache/Nginx to allow CGI scripts (usually in /cgi-bin/).


 Create a database and table:

sql

CREATE DATABASE school;


USE school;
CREATE TABLE students (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(50),
grade VARCHAR(5)
);

2. Full CGI Script ([Link])

python
#!/usr/bin/env python3
import [Link]
import cgi, html

print("Content-Type: text/html")
print() # Blank line after headers

# Connect to MySQL
conn = [Link](
host="localhost",
user="root",
password="yourpassword",
database="school"
)
cursor = [Link]()

# Parse form data


form = [Link]()
action = [Link]("action", "list")

def list_students():
[Link]("SELECT * FROM students")
print("<h2>Student List</h2>")
print("<table border='1'><tr><th>ID</th><th>Name</th><th>Grade</th></tr>")
for (id, name, grade) in [Link]():

80
print(f"<tr><td>{id}</td><td>{[Link](name)}</td><td>{[Link](grade)}</td></tr>")
print("</table>")

def add_student():
name = [Link]("name")
grade = [Link]("grade")
if name and grade:
[Link]("INSERT INTO students (name, grade) VALUES (%s, %s)", (name, grade))
[Link]()
print("<p>Student added successfully!</p>")
else:
print("<p>Please provide name and grade.</p>")

def update_student():
sid = [Link]("id")
grade = [Link]("grade")
if sid and grade:
[Link]("UPDATE students SET grade=%s WHERE id=%s", (grade, sid))
[Link]()
print("<p>Student updated successfully!</p>")
else:
print("<p>Please provide ID and new grade.</p>")

def delete_student():
sid = [Link]("id")
if sid:
[Link]("DELETE FROM students WHERE id=%s", (sid,))
[Link]()
print("<p>Student deleted successfully!</p>")
else:
print("<p>Please provide ID to delete.</p>")

# Routing based on action


if action == "add":
add_student()
elif action == "update":
update_student()
elif action == "delete":
delete_student()
else:
list_students()

# Navigation form

81
print("""
<h3>Actions</h3>
<form method="post">
<input type="hidden" name="action" value="add">
Name: <input name="name"> Grade: <input name="grade">
<button type="submit">Add Student</button>
</form>

<form method="post">
<input type="hidden" name="action" value="update">
ID: <input name="id"> New Grade: <input name="grade">
<button type="submit">Update Student</button>
</form>

<form method="post">
<input type="hidden" name="action" value="delete">
ID: <input name="id">
<button type="submit">Delete Student</button>
</form>
""")

[Link]()
[Link]()

SMTP – Sending Email Using Python

1. What is SMTP?

SMTP stands for Simple Mail Transfer Protocol.

SMTP is a protocol used to send emails from:

 a client (Python program)


 to a mail server (Gmail, Outlook, etc.)

Simple Definition (for students)

SMTP is used to send emails over the Internet.

2. Why Use Python for Sending Emails?

82
 Python provides built-in libraries
 Easy to automate email sending
 Used for notifications, alerts, reports
 Supports text, HTML, and attachments

3. SMTP Working Flow (Important for Understanding)

Python Program

SMTP Server (Gmail / Outlook)

Recipient Mail Server

Receiver Inbox

4. Python Libraries Used for Email

Library Purpose

smtplib Connect to SMTP server

[Link] Create email

[Link] Email body

[Link] Multiple parts

[Link] Attachments

PART 1: Sending a Simple Email Using Python

Step-by-Step Explanation

Step 1: Import Required Libraries


import smtplib
from [Link] import EmailMessage

83
Step 2: Create Email Message
msg = EmailMessage()
msg['From'] = "sender@[Link]"
msg['To'] = "receiver@[Link]"
msg['Subject'] = "Test Email from Python"

msg.set_content("Hello! This email is sent using Python SMTP.")

Step 3: Connect to SMTP Server & Send Email


server = [Link]("[Link]", 587)
[Link]()
[Link]("sender@[Link]", "your_app_password")
server.send_message(msg)
[Link]()

print("Email sent successfully")

Teaching Notes

 [Link] → Gmail SMTP server


 587 → TLS port
 starttls() → Secure connection
 Use App Password, not Gmail password

Sending an HTML Email Using Python

HTML emails allow:

 Bold text
 Colors
 Tables
 Images

Example: Sending HTML Email

import smtplib
from [Link] import EmailMessage

84
msg = EmailMessage()
msg['From'] = "sender@[Link]"
msg['To'] = "receiver@[Link]"
msg['Subject'] = "HTML Email from Python"

html_content = """
<html>
<body>
<h2 style="color:blue;">Welcome!</h2>
<p>This is an <b>HTML email</b> sent using Python.</p>
</body>
</html>
"""

msg.add_alternative(html_content, subtype='html')

server = [Link]("[Link]", 587)


[Link]()
[Link]("sender@[Link]", "your_app_password")
server.send_message(msg)
[Link]()

print("HTML Email sent")

Teaching Points

 add_alternative() → Used for HTML content


 Browser renders HTML in email client

Sending Email with Attachments Using Python

What is an Attachment?

A file sent along with an email (PDF, image, text file, etc.)

Example: Sending Email with Attachment

import smtplib

85
from [Link] import EmailMessage

msg = EmailMessage()
msg['From'] = "sender@[Link]"
msg['To'] = "receiver@[Link]"
msg['Subject'] = "Email with Attachment"

msg.set_content("Please find the attachment below.")

# Attach file
with open("[Link]", "rb") as file:
file_data = [Link]()
file_name = [Link]

msg.add_attachment(
file_data,
maintype="application",
subtype="pdf",
filename=file_name
)

server = [Link]("[Link]", 587)


[Link]()
[Link]("sender@[Link]", "your_app_password")
server.send_message(msg)
[Link]()

print("Email with attachment sent")

-------------------------------------------------------------------------------------------------------------------------------

Regular Expressions in Python


1. What is a Regular Expression?

A Regular Expression (Regex) is a pattern used to match, search, extract, or validate text.

Simple Definition (for students)

Regex is a special sequence of characters used to find patterns in text.

86
2. Why Use Regex?

Explain to students:

 To search text quickly


 To extract required information
 To validate user input
 To parse logs, IP addresses, emails, URL

3. Python Module for Regex

Python provides the re module for regular expressions.

import re

4. Basic Regex Functions (Very Important)

Function Purpose

[Link]() Matches at beginning

[Link]() Searches anywhere

[Link]() Returns all matches

[Link]() Iterator of matches

[Link]() Replace text

5. Pattern Matching & Searching

Example 1: [Link]() – Match at Start


import re

text = "Python programming"


result = [Link]("Python", text)

if result:
print("Match found")
else:

87
print("No match")

🧠 Teaching point:
match() checks only at beginning.

Example 2: [Link]() – Search Anywhere


import re

text = "I am learning Python"


result = [Link]("Python", text)

if result:
print("Found at position:", [Link]())

Example 3: [Link]() – All Matches


import re

text = "Python is easy. Python is powerful."


result = [Link]("Python", text)
print(result)

7. Real-Time Parsing Using Regex

(Networking / System Data)

Example 1: Extract IP Address from Log


import re

log = "Connection from [Link] successful"


ip = [Link](r"\d+\.\d+\.\d+\.\d+", log)

print("IP Address:", [Link]())

 Real-time use:

 Network logs
 Firewall monitoring

88
Example 2: Extract Date from System Log
import re

log = "Error occurred on 12-08-2025 at server"


date = [Link](r"\d{2}-\d{2}-\d{4}", log)

print("Date:", [Link]())

Example 3: Extract Port Numbers


import re

log = "Server listening on port 8080"


port = [Link](r"\d{4}", log)

print("Port:", [Link]())

8. Real-Time Parsing (Email, URL, User Data)

Example: Extract Email IDs from Text


import re

text = "Contact us at support@[Link] or admin@[Link]"


emails = [Link](r"\S+@\S+", text)

print(emails)

9. Validation Concepts Using Regex

(Very Important for Applications)

9.1 Email Validation

import re

email = "user@[Link]"

pattern = r"^[\w\.-]+@[\w\.-]+\.\w+$"

89
if [Link](pattern, email):
print("Valid Email")
else:
print("Invalid Email")

9.2 Mobile Number Validation (India)

import re

mobile = "9876543210"

if [Link](r"^[6-9]\d{9}$", mobile):
print("Valid Mobile Number")
else:
print("Invalid Mobile Number")

9.3 Password Validation

Rules:

 At least 8 characters
 One digit
 One uppercase letter

import re

password = "Python123"

pattern = r"^(?=.*[A-Z])(?=.*\d).{8,}$"

if [Link](pattern, password):
print("Strong Password")
else:
print("Weak Password")

9.4 Username Validation

import re

username = "user_01"

90
if [Link](r"^[a-zA-Z0-9_]+$", username):
print("Valid Username")
else:
print("Invalid Username")

10. Replacing Data using Regex

import re

text = "My number is 9876543210"


new_text = [Link](r"\d{10}", "XXXXXXXXXX", text)

print(new_text)

Real-World Applications

 Form validation
 Log file analysis
 Network monitoring
 Data cleaning
 Web scraping

1. Real-Time Hack (Automation / Real-Time Tasks)

 In programming, “real-time hack” usually means automating tasks that run instantly
when triggered.
 Examples:
o Monitoring stock prices and alerting when they change.
o Auto-downloading new emails or files.
o Real-time chat monitoring.

In Python, you use schedulers (schedule, time, threading) or event-driven libraries to run tasks
continuously.

Example :

import time

def check_status():
print("Checking system status...")

while True:

91
check_status()
[Link](5) # runs every 5 seconds

Web Scraping (Very Important & Easy)

What is Web Scraping?

Web scraping means collecting data automatically from websites using Python.

Instead of copying data manually:

 Python fetches
 Python extracts
 Python stores data

Real-World Uses

 Price comparison (Amazon, Flipkart)


 News headlines collection
 Job listings
 Weather data

Libraries Used

 requests → download webpage


 BeautifulSoup → extract data

Simple Example: Get Website Title

Python libraries: requests (fetch HTML), BeautifulSoup (parse HTML), selenium (simulate browser).

Example: Scraping headlines from a news site.

import requests

from bs4 import BeautifulSoup

url = "[Link]

response = [Link](url)

92
soup = BeautifulSoup([Link], "[Link]")

for headline in soup.find_all("h2"):

print([Link])

3 Chatbot & Language Translation

3.1 Chatbot (Simple Understanding)

What is a Chatbot?

A chatbot is a program that responds automatically to user messages.

Simple Real-World Example

 Customer support bots


 College enquiry bots
 WhatsApp auto replies

Very Simple Python Chatbot


user = input("You: ")

if [Link]() == "hi":
print("Bot: Hello!")
elif [Link]() == "bye":
print("Bot: Goodbye!")
else:
print("Bot: I don't understand")

3.2 Language Translation

What is Language Translation?

Converting text from one language to another using Python.

93
Real-World Uses

 Google Translate
 Multilingual apps
 Chatbots with multiple languages

Example: English to Tamil Translation


from googletrans import Translator

translator = Translator()
result = [Link]("Hello", dest="ta")

print([Link])

4️ Finding Similarity Ratio Between Text (Very Important)

What is Text Similarity?

Measuring how similar two texts are.

Real-World Uses

 Plagiarism checking
 Resume matching
 Chatbot intent detection
 Document comparison

4.1 Simple Similarity Using difflib

from difflib import SequenceMatcher

text1 = "Python programming"


text2 = "Python program"

similarity = SequenceMatcher(None, text1, text2).ratio()


print("Similarity:", similarity)

94
Output
Similarity: 0.88

4.2 Similarity Percentage

similarity_percent = similarity * 100


print("Similarity %:", similarity_percent)

5️ How These Are Connected in Real Life

Concept Real-Time Use

Ethical hacking Security checks

Web scraping Data collection

Chatbot Auto responses

Translation Multilingual support

Text similarity Plagiarism detection

Tagging Sentence to Find Keywords

(Keyword Extraction)
What is it?

Keyword tagging means identifying important words from a sentence.

Real-World Uses

 Search engines
 Resume screening
 Chatbots

Simple Logic (Explain to Students)

1. Split sentence into words


2. Remove common words (is, am, the, and)

95
3. Remaining words are keywords

Example 1: Keyword Tagging (Basic)


sentence = "Python is used for web development and data analysis"

stopwords = ["is", "for", "and"]


keywords = []

for word in [Link]():


if [Link]() not in stopwords:
[Link](word)

print("Keywords:", keywords)

Example 2: Keyword Frequency


sentence = "python python programming python"

words = [Link]()
freq = {}

for w in words:
freq[w] = [Link](w, 0) + 1

print(freq)

Example 3: Highlight Keywords


sentence = "Python programming language"
keywords = ["Python", "programming"]

for word in [Link]():


if word in keywords:
print(word, "→ keyword")

2️ Bubble Sort Algorithm

What is Bubble Sort?

Bubble sort is a simple sorting algorithm that repeatedly swaps adjacent elements if they are in
wrong order.

96
Real-World Example

 Sorting marks
 Sorting prices
 Ranking scores

Algorithm Steps

1. Compare two numbers


2. Swap if needed
3. Repeat until sorted

Example 1: Bubble Sort


arr = [5, 2, 9, 1]

for i in range(len(arr)):
for j in range(0, len(arr)-1):
if arr[j] > arr[j+1]:
arr[j], arr[j+1] = arr[j+1], arr[j]

print(arr)

Example 2: Bubble Sort with Input


arr = list(map(int, input("Enter numbers: ").split()))

for i in range(len(arr)):
for j in range(len(arr)-1):
if arr[j] > arr[j+1]:
arr[j], arr[j+1] = arr[j+1], arr[j]

print("Sorted:", arr)

Example 3: Descending Order


arr = [3, 1, 4]

for i in range(len(arr)):
for j in range(len(arr)-1):
if arr[j] < arr[j+1]:
arr[j], arr[j+1] = arr[j+1], arr[j]

97
print(arr)

3️QR Code Generator

What is QR Code?

QR code stores information like text, URL, contact in image format.

Real-World Uses

 Payment apps
 Event tickets
 Website links

Install Library
pip install qrcode

Example 1: Generate QR Code


import qrcode

data = "[Link]
img = [Link](data)

[Link]("python_qr.png")

Example 2: QR for Text


import qrcode

img = [Link]("Welcome to Python Class")


[Link]("text_qr.png")

Example 3: QR for Contact Info


import qrcode

contact = "Name: Priya\nPhone: 9876543210"


img = [Link](contact)
[Link]("contact_qr.png")

4️Spell Checker
98
What is Spell Checker?

Program that detects and corrects spelling mistakes.

Real-World Uses

 Word processors
 Chat applications
 Email clients

Install Library
pip install textblob

Example 1: Spell Check


from textblob import TextBlob

text = "I lovv python progrmming"


blob = TextBlob(text)

print([Link]())

Example 2: Word Correction


from textblob import Word

word = Word("progrmming")
print([Link]())

Example 3: Sentence Correction


sentence = TextBlob("Ths is a smple sentnce")
print([Link]())

5️Scraping Wikipedia

99
What is Web Scraping?

Automatically extracting information from websites.

Real-World Uses

 Research
 Data collection
 Automation

Example 1: Wikipedia Summary


import wikipedia

result = [Link]("Python programming language", sentences=2)


print(result)

Example 2: Wikipedia Search


import wikipedia

print([Link]("Artificial Intelligence"))

Example 3: Page Title


import wikipedia

page = [Link]("Python")
print([Link])

6️Anagram Program

What is Anagram?

Two words having same letters but different order.

Example:

 listen → silent
 race → care

100
Example 1: Check Anagram
word1 = "listen"
word2 = "silent"

if sorted(word1) == sorted(word2):
print("Anagram")
else:
print("Not anagram")

Example 2: Ignore Case


w1 = "Race"
w2 = "Care"

if sorted([Link]()) == sorted([Link]()):
print("Anagram")

Example 3: Sentence Anagram


s1 = "Dormitory".replace(" ", "").lower()
s2 = "Dirty room".replace(" ", "").lower()

print(sorted(s1) == sorted(s2))

7️Screenshot App in Python

What is Screenshot App?

Captures screen image using Python.

Real-World Uses

 Bug reporting
 Online teaching
 Automation testing

Install Library
pip install pyautogui

101
Example 1: Take Screenshot
import pyautogui

screenshot = [Link]()
[Link]("[Link]")

Example 2: Screenshot with Name


import pyautogui

img = [Link]("my_screen.png")

Example 3: Screenshot after Delay


import pyautogui
import time

[Link](5)
[Link]("delay_screen.png")

Python for Networking

Python has built-in libraries like socket that allow you to create networking applications.

 Networking basics: Communication between computers over TCP/IP.


 Python socket module: Provides low-level networking interface.
 Use cases: Chat applications, file transfer, web servers.

Example: Simple TCP Client


import socket

client = [Link](socket.AF_INET, socket.SOCK_STREAM)


[Link](("localhost", 12345))
[Link](b"Hello Server")
response = [Link](1024)
print("Received:", [Link]())
[Link]()
-------------------------------------------------------------------------------------------------------------------------------

102
Example: Simple TCP Server
import socket

server = [Link](socket.AF_INET, socket.SOCK_STREAM)


[Link](("localhost", 12345))
[Link](1)
print("Server listening...")

conn, addr = [Link]()


print("Connected by", addr)
data = [Link](1024)
print("Received:", [Link]())
[Link](b"Hello Client")
[Link]()

Server-Client Program

A server-client program demonstrates networking:

 Server: Listens for connections.


 Client: Connects and sends requests.
 Communication happens via sockets.

Already shown above with TCP server and client examples.

-------------------------------------------------------------------------------------------------------------------------------

Introduction to Django

 Django is a high-level Python web framework.


 It helps build secure, scalable web applications quickly.
 Features:
o ORM (Object Relational Mapper) for database access.
o Built-in admin panel.
o URL routing, templates, forms, authentication.

Django follows the MVC pattern (Model-View-Controller), but in Django it’s often called MTV
(Model-Template-View).

103
Django and Python

 Django is written in Python and uses Python for all logic.


 Python provides simplicity, readability, and a huge ecosystem.
 Django leverages Python’s strengths for rapid web development.

MVC Model in Django

 Model: Defines data structure (database tables).


 View: Handles business logic and returns responses.
 Controller: In Django, the framework itself acts as the controller (URL routing).
 Django’s version is MTV:
o Model → Database layer.
o Template → Presentation layer (HTML).
o View → Business logic layer.

Views in Django

 A view is a Python function or class that receives a request and returns a response.
 Example:

from [Link] import HttpResponse

def hello(request):
return HttpResponse("Hello, Django!")

Static Templates in Django

 Templates: HTML files with placeholders for dynamic content.


 Static files: CSS, JavaScript, images.
 Django uses the template engine to render HTML with data.

Example Template ([Link])


<!DOCTYPE html>
<html>
<head>
<title>Hello Page</title>
</head>
<body>
<h1>Hello, {{ name }}!</h1>
</body>
</html>

104
Example View Rendering Template
from [Link] import render

def hello(request):
return render(request, "[Link]", {"name": "Alice"})

Django Basics: HTTP Response vs Template Rendering

1. HTTP Response (Direct Output)

 Django views can return a simple HttpResponse object.


 This is useful for quick testing or returning plain text/HTML directly.

Example:
from [Link] import HttpResponse

def hello(request):
return HttpResponse("<h1>Hello, Django!</h1>")

When you visit /hello/, the browser shows “Hello, Django!” directly.

2. Template Files (HTML Rendering)

 Instead of writing HTML inside Python, Django uses template files.


 Templates are stored in a templates/ directory inside your app.
 Django’s template engine allows placeholders ({{ }}) and logic ({% %}).

Example Template ([Link])


<!DOCTYPE html>
<html>
<head>
<title>Hello Page</title>
</head>
<body>
<h1>Hello, {{ name }}!</h1>
</body>
</html>

105
3. Rendering Templates in Views

 Use render() to load an HTML file and pass data.

Example View:
from [Link] import render

def hello(request):
context = {"name": "Alice"} # data for template
return render(request, "[Link]", context)

This will replace {{ name }} in the template with “Alice”.

4. Project Setup Steps

1. Create a Django project:

django-admin startproject myproject

2. Create an app:

python [Link] startapp myapp

3. In myapp/[Link], add the view (like above).


4. In myproject/[Link], map the URL:

from [Link] import path


from myapp import views

urlpatterns = [
path("hello/", [Link]),
]

5. Create a templates folder inside myapp and put [Link] there.


6. Run server:

python [Link] runserver

106
Static Files in Django

1. What are Static Files?

 Static files = resources like CSS, JavaScript, images that don’t change dynamically.
 Django has a built-in system to manage them.
 You place them in a folder named static/ inside your app.

Example project structure:

myproject/
myapp/
static/
myapp/
[Link]
[Link]
templates/
[Link]

2. Adding CSS

 Create a CSS file inside static/myapp/[Link]:

css

body {
background-color: #f0f0f0;
font-family: Arial, sans-serif;
}
h1 {
color: blue;
}

 Load CSS in your template ([Link]):

{% load static %}
<!DOCTYPE html>
<html>
<head>
<title>Home Page</title>
<link rel="stylesheet" href="{% static 'myapp/[Link]' %}">
</head>
<body>
<h1>Welcome to Django!</h1>

107
</body>
</html>

3. Adding Images

 Place an image in static/myapp/[Link].


 Use it in your template:

{% load static %}
<img src="{% static 'myapp/[Link]' %}" alt="Logo" width="200">

4. Anchor Tag Creation (Links)

 Anchor tags (<a>) create hyperlinks.


 Example in Django template:

<a href="[Link] Django Official Site</a>

 Linking to another Django view (using url tag):

{% load static %}
<a href="{% url 'about' %}">About Us</a>

Here, 'about' is the name of a view defined in [Link].

5. [Link] Example

from [Link] import path


from myapp import views

urlpatterns = [
path("", [Link], name="home"),
path("about/", [Link], name="about"),
]
-------------------------------------------------------------------------------------------------------------------------------

Django + MySQL Database Connectivity

1. Setup

 Install MySQL connector:

pip install mysqlclient

 In [Link], configure database:


108
DATABASES = {
'default': {
'ENGINE': '[Link]',
'NAME': 'school',
'USER': 'root',
'PASSWORD': 'yourpassword',
'HOST': 'localhost',
'PORT': '3306',
}
}

2. Creating Database and Table (Model)

In Django, tables are defined as models.

# myapp/[Link]
from [Link] import models

class Student([Link]):
name = [Link](max_length=50)
grade = [Link](max_length=5)

Run migrations:

python [Link] makemigrations


python [Link] migrate

This creates the students table in MySQL.

3. CRUD Operations

Insert Data (Create)


# myapp/[Link]
from [Link] import HttpResponse
from .models import Student

def add_student(request):
s = Student(name="Alice", grade="A")
[Link]()
return HttpResponse("Student added successfully!")

109
Fetch Data (Read)
def list_students(request):
students = [Link]()
output = "<h2>Student List</h2>"
for s in students:
output += f"<p>{[Link]} - {[Link]} - {[Link]}</p>"
return HttpResponse(output)

Update Data
def update_student(request, sid):
s = [Link](id=sid)
[Link] = "B"
[Link]()
return HttpResponse("Student updated successfully!")
Delete Data
def delete_student(request, sid):
s = [Link](id=sid)
[Link]()
return HttpResponse("Student deleted successfully!")

Mail Sending in Django

Configure email in [Link]:

EMAIL_BACKEND = '[Link]'
EMAIL_HOST = '[Link]'
EMAIL_PORT = 587
EMAIL_USE_TLS = True
EMAIL_HOST_USER = 'your_email@[Link]'
EMAIL_HOST_PASSWORD = 'your_app_password'

Send mail in a view:

from [Link] import send_mail

def send_welcome_email(request):
send_mail(
"Welcome to Django",
"Hello, you have registered successfully!",
"your_email@[Link]",
["receiver@[Link]"],

110
fail_silently=False,
)
return HttpResponse("Email sent successfully!")

User Authentication (Register & Login)


Register (Sign Up)
from [Link] import User
from [Link] import HttpResponse

def register(request):
user = [Link].create_user(username="john", password="mypassword",
email="john@[Link]")
[Link]()
return HttpResponse("User registered successfully!")
Login
from [Link] import authenticate, login

def user_login(request):
user = authenticate(username="john", password="mypassword")
if user is not None:
login(request, user)
return HttpResponse("Login successful!")
else:
return HttpResponse("Invalid credentials")
Logout
from [Link] import logout

def user_logout(request):
logout(request)
return HttpResponse("Logged out successfully!")

111
112
113

You might also like