Python Syllabus
Python Syllabus
1
SESSION 1: PYTHON – Introduction & SESSION 14 : PYTHON CGI INTRODUCTION –
Installation in Python Writing python program for CGI applications
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
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:
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
5
o Search for "IDLE" in Start Menu
o Opens interactive Python shell
o File → New File to create scripts
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:
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:
#Dynamic Input
age = int(input(“enter your age :”))
price =float(input(“enter a price :”))
7
Scenario: A simple ATM withdrawal system.
Static Example:
Python
Dynamic Example:
Python
2. String (str)
Static Example:
greeting = "Hello"
name = "Student"
message = greeting + " " + name
print(message)
Dynamic Example:
8
3. Boolean (bool)
Static Example:
is_sunny = True
is_raining = False
print("Is it a clear day?", is_sunny)
Dynamic Example:
[Link] []
Static Example:
Dynamic Example:
9
. [Link] ()
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:
6. Set {}
Static Example:
Dynamic Example:
10
7. Dictionary {"key": "value"}
Static Example:
Dynamic Example:
The Formula
a + bj
Static Example
11
# Defining complex numbers
z1 = 3 + 5j
z2 = 2 + 3j
# Addition
result = z1 + z2
Dynamic Example
In a dynamic example, we take user input. Since input() returns a string, we use the complex()
constructor to convert it.
# Performing multiplication
product = c1 * c2
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.
12
1. Integer Conversion (int)
Static Example:
price = 99.99
converted_price = int(price) # Truncates decimals
print("Static Integer:", converted_price) # Output: 99
Dynamic Example:
Static Example:
whole_number = 10
decimal_number = float(whole_number)
print("Static Float:", decimal_number) # Output: 10.0
Dynamic Example:
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:
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:
Dynamic Example:
# Taking multiple values from user and converting to a Set to get 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!")
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 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.
square = lambda x: x * x
print(square(10)) # Output: 100
Dynamic Example:
Higher-order functions
Functions that take functions as arguments or return functions (map, filter, or user functions)
Example:
def square(n):
return n * n
16
def apply(func, value): /// arguments
return func(value)
result = apply(square, 5)
print(result) //25
Explanation :
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
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")
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)
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
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)
0, 1, 1, 2, 3, 5, 8, 13, ...
[Link](6)
2 . fib(5)
[Link](4)
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
Local Variables
Local variables are defined inside a function and accessible only within that function.
def func_local():
x = 10 # local
print('Inside:', x)
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()
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.
The math module contains functions for mathematical operations that go beyond Python's
basic arithmetic (+, -, *, /). You must import it (import math) before use.
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
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]).
Strings are immutable sequences of characters. The string type has many built-in methods for
inspecting and transforming text.
24
Very useful methods
Examples
STRIP ()
Examples:
CHANGE CASE
Examples:
text = "hello python students"
25
split(sep) — Split into List :
What it does:
Examples:
text = "apple,banana,grapes"
print([Link](","))
# ['apple', 'banana', 'grapes']
print("Python is fun".split())
# ['Python', 'is', 'fun']
Example:
words = ["Python", "is", "fun"]
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."
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:
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
Examples
from datetime import datetime, date, timedelta
# 2. format date
now = [Link]()
print([Link]("%d-%m-%Y %H:%M"))
# 4. add days
print([Link]() + timedelta(days=7))
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.
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 using third-party libraries is to convert static PDF documents into
structured, machine-readable data for automation, analysis, and reuse.
PDF parsing
Text decoding
Layout analysis
Table detection
OCR (for scanned PDFs) – OCR stands for Optical Character Recognition.
29
Example with PyPDF2 (text extraction)
import PyPDF2
Explanation:
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
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])
Explanation:
Short exercise
OPERATORS IN PYTHON
1. Operators in Python
32
1.1 Arithmetic Operators
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
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)
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
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")
num = 10
if num % 2 == 0:
print("Even")
else:
34
print("Odd")
marks = 35
if marks >= 40:
print("Pass")
else:
print("Fail")
marks = 75
if marks >= 90:
print("Grade A")
elif marks >= 60:
print("Grade B")
else:
print("Grade C")
3. Looping Statements
for i in range(5):
print(i)
for ch in "Python":
print(ch)
i=1
while i <= 5:
print(i)
i =i+1 // i+=1
count = 3
while count > 0:
print("Countdown:", count)
count -= 1
35
4.1 break statement
Modules
What a module is ?
A module is simply a .py file containing functions, classes, or variables. Use import
module_name to use it.
36
return a + b
# [Link]
def add(a, b):
return a + b
import mymath
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).
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:
Dynamic Example:
What is a File?
Examples:
38
.txt → text file
.csv → table data
.log → logs
.json → structured data
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
Syntax
file_object = open("filename", "mode")
Example
f = open("[Link]", "r")
a) write()
f = open("[Link]", "w")
[Link]("Welcome to Python")
[Link]()
b) writelines()
f = open("[Link]", "w")
[Link](["Hello\n", "Python\n", "File Handling"])
[Link]()
-------------------------------------------------------------------------------------------------------------------------------
Reading Files
a) read()
f = open("[Link]", "r")
content = [Link]()
print(content)
[Link]()
40
b) readline()
f = open("[Link]", "r")
print([Link]())
print([Link]())
[Link]()
c) readlines()
f = open("[Link]", "r")
lines = [Link]()
print(lines)
[Link]()
-------------------------------------------------------------------------------------------------------------------------------
[Link]()
-------------------------------------------------------------------------------------------------------------------------------
a) tell()
f = open("[Link]", "r")
print([Link]())
[Link]()
41
b) seek()
f = open("[Link]", "r")
[Link](0)
print([Link]())
[Link]()
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]")
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
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
Changing Directory
Changing Directory
Syntax
[Link]("path")
Example
[Link]("D:/Python")
print([Link]())
44
Listing Directory Contents
Example
print([Link]())
List Specific Directory
print([Link]("D:/Python"))
-------------------------------------------------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------------------------------------------------
Renaming a Directory
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]")
-------------------------------------------------------------------------------------------------------------------------------
46
-------------------------------------------------------------------------------------------------------------------------------
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
try:
x = 10 / 0
except Block
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
try:
result = "hello" + 5 # cannot add str and int
except TypeError:
print("Caught a TypeError: wrong type used!")
IndexError
try:
nums = [1, 2, 3]
print(nums[5]) # out of range
except IndexError:
print("Caught an IndexError: index out of range!")
-------------------------------------------------------------------------------------------------------------------------------
KeyError
try:
data = {"a": 1}
print(data["b"]) # key not found
except KeyError:
print("Caught a KeyError: key not found!")
-------------------------------------------------------------------------------------------------------------------------------
FileNotFoundError
try:
f = open("[Link]")
except FileNotFoundError:
print("Caught a FileNotFoundError: file not found!")
48
-------------------------------------------------------------------------------------------------------------------------------
AttributeError
try:
text = "hello"
[Link]("!") # strings don’t have append()
except AttributeError:
print("Caught an AttributeError: invalid attribute!")
ImportError / ModuleNotFoundError
try:
import non_existing_module
except ImportError:
print("Caught an ImportError: module not found!")
-------------------------------------------------------------------------------------------------------------------------------
else Block
try:
num = int("10")
except ValueError:
print("Conversion failed.")
else:
print("Conversion successful:", num)
-------------------------------------------------------------------------------------------------------------------------------
finally Block
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)
-------------------------------------------------------------------------------------------------------------------------------
Suppose you want to enforce that a person’s age must be at least 18 to register for a service.
50
if age < 18:
raise UnderAgeError(age)
else:
print("Registration successful!")
Error vs Exception
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 :
51
Detailed Explanations of OOP Concepts
class Car:
[Link] = brand
[Link] = model
class Dog:
[Link] = name
def bark(self):
dog1 = Dog("Buddy")
52
class Student:
[Link] = name
[Link] = grade
s1 = Student("Alice", "A")
s2 = Student("Bob", "B")
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.
class Animal:
def speak(self):
class Dog(Animal):
def speak(self):
d = Dog()
class Vehicle:
53
def move(self):
class Car(Vehicle):
def move(self):
class SportsCar(Car):
def move(self):
sc = SportsCar()
class Father:
def skills(self):
return "Gardening"
class Mother:
def skills(self):
return "Cooking"
def skills(self):
c = Child()
[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.
class BankAccount:
self.__balance += amount
def get_balance(self):
return self.__balance
acc = BankAccount(1000)
[Link](500)
print(acc.get_balance()) # 1500
class Employee:
[Link] = name
e = Employee("John", 5000)
55
# Example 3: Encapsulation with getter/setter
class Student:
self.__name = name
def get_name(self):
return self.__name
self.__name = new_name
s = Student("Alice")
print(s.get_name()) # Alice
s.set_name("Bob")
print(s.get_name()) # Bob
[Link]
class Bird:
def sound(self):
return "Chirp"
class Dog:
56
def sound(self):
return "Bark"
print(len("Hello")) # 5
print(len([1,2,3])) # 3
print(10 + 20) # 30
5. Data Abstraction
class Shape(ABC):
@abstractmethod
def area(self):
pass
class Circle(Shape):
self.r = r
def area(self):
57
return 3.14 * self.r * self.r
c = Circle(5)
print([Link]()) # 78.5
class Vehicle(ABC):
@abstractmethod
@abstractmethod
class Car(Vehicle):
car = Car()
print([Link](), [Link]())
class Animal(ABC):
@abstractmethod
def sleep(self):
return "Sleeping..."
class Dog(Animal):
d = Dog()
58
print([Link](), [Link]()) # Bark Sleeping...
6. Overloading
return a + b + c
print(add(5)) #5
print(add(5, 10)) # 15
class Book:
[Link] = pages
b1 = Book(100)
b2 = Book(200)
class Calculator:
59
return sum(args)
c = Calculator()
print([Link](2,3)) #5
print([Link](2,3,4,5)) # 14
class Parent:
def greet(self):
class Child(Parent):
def greet(self):
c = Child()
class Animal:
def sound(self):
60
class Dog(Animal):
def sound(self):
d = Dog()
class Shape:
def area(self):
return "Undefined"
class Square(Shape):
[Link] = side
def area(self):
for s in shapes:
print([Link]()) # Undefined, 16
-------------------------------------------------------------------------------------------------------------------------------
Multithreading
What is Multithreading?
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
import threading
def print_numbers():
for i in range(5):
print("Number:", i)
t = [Link](target=print_numbers)
[Link]()
def worker(name):
threads = []
for i in range(3):
62
t = [Link](target=worker, args=(i,))
[Link](t)
[Link]()
for t in threads:
[Link]()
import time
def delayed_task():
[Link](2)
t = [Link](target=delayed_task)
[Link]()
[Link]()
Definition
Forking threads means creating and running multiple threads to perform tasks concurrently.
import threading
63
def task(name):
for i in range(3):
t = [Link](target=task, args=(i,))
[Link]()
def task1():
print("Task 1 running")
def task2():
print("Task 2 running")
t1 = [Link](target=task1)
t2 = [Link](target=task2)
[Link]()
[Link]()
[Link]()
[Link]()
def count_up(name):
for i in range(3):
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.
Race condition
Incorrect output
Solution
Locks (Lock)
Semaphores
import threading
lock = [Link]()
shared_counter = 0
def increment():
global shared_counter
for _ in range(1000):
[Link]()
shared_counter += 1
65
[Link]()
lock = [Link]()
def safe_print(msg):
with lock:
print(msg)
[Link](); [Link]()
[Link](); [Link]()
def limited_task(name):
with semaphore:
print(f"{name} is running")
66
-------------------------------------------------------------------------------------------------------------------------------
What is MySQL?
MySQL is a relational database that stores data in tables (rows and columns) and uses SQL
queries.
import [Link]
conn = [Link](
host="localhost",
user="root",
password="password",
database="student_db"
)
67
print("Database connected")
Explanation
cursor = [Link]()
-------------------------------------------------------------------------------------------------------------------------------
CRUD Operations in MySQL using Python
sql = "INSERT INTO students (id, name, age) VALUES (%s, %s, %s)"
values = (1, "Priya", 21)
[Link](sql, values)
[Link]()
print("Record inserted")
[Link](sql, data)
[Link]()
[Link](
"INSERT INTO students VALUES (4, 'Kumar', 23)"
68
)
[Link]()
[Link](
"UPDATE students SET age=22 WHERE id=1"
)
[Link]()
69
-------------------------------------------------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------------------------------------------------
What is MongoDB?
import pymongo
client = [Link]("mongodb://localhost:27017/")
db = client["student_db"]
collection = db["students"]
70
print("MongoDB connected")
Explanation
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
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.
CREATE Query
ALTER Query
DROP Query
73
TRUNCATE Query
INSERT Query
UPDATE Query
DELETE Query
Deletes records.
74
SELECT Query
WHERE Clause
Filters records.
ORDER BY
Sorts records.
LIMIT
4. Aggregate Functions
Function Description
AVG() Average
MIN() Minimum
75
Function Description
MAX() Maximum
5. GROUP BY Clause
6. HAVING Clause
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];
76
id INT PRIMARY KEY,
name VARCHAR(50) NOT NULL,
age INT CHECK(age > 18)
);
9. Subqueries
Python CGI
1. What is CGI?
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.
CGI is a way for a web server to run a program and show its output on a webpage.
77
Diagram Representation
Browser
↓
Web Server
↓
Python CGI Script
↓
HTML Output
↓
Browser
-------------------------------------------------------------------------------------------------------------------------------
Python CGI means using Python programs as CGI scripts to generate dynamic web content.
Explain to students:
Easy syntax
Readable code
Beginner-friendly
Powerful libraries
Platform independent
78
1. Web Server (Apache / IIS)
2. Python installed
3. CGI enabled in server
4. Python files stored in cgi-bin folder
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>")
#!/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>")
This example shows a Student Management System with Create, Read, Update, Delete (CRUD)
operations using MySQL.
1. Setup
79
pip install mysql-connector-python
sql
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]()
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>")
# 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]()
1. What is SMTP?
82
Python provides built-in libraries
Easy to automate email sending
Used for notifications, alerts, reports
Supports text, HTML, and attachments
Python Program
↓
SMTP Server (Gmail / Outlook)
↓
Recipient Mail Server
↓
Receiver Inbox
Library Purpose
[Link] Attachments
Step-by-Step Explanation
83
Step 2: Create Email Message
msg = EmailMessage()
msg['From'] = "sender@[Link]"
msg['To'] = "receiver@[Link]"
msg['Subject'] = "Test Email from Python"
Teaching Notes
Bold text
Colors
Tables
Images
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')
Teaching Points
What is an Attachment?
A file sent along with an email (PDF, image, text file, etc.)
import smtplib
85
from [Link] import EmailMessage
msg = EmailMessage()
msg['From'] = "sender@[Link]"
msg['To'] = "receiver@[Link]"
msg['Subject'] = "Email with Attachment"
# 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
)
-------------------------------------------------------------------------------------------------------------------------------
A Regular Expression (Regex) is a pattern used to match, search, extract, or validate text.
86
2. Why Use Regex?
Explain to students:
import re
Function Purpose
if result:
print("Match found")
else:
87
print("No match")
🧠 Teaching point:
match() checks only at beginning.
if result:
print("Found at position:", [Link]())
Real-time use:
Network logs
Firewall monitoring
88
Example 2: Extract Date from System Log
import re
print("Date:", [Link]())
print("Port:", [Link]())
print(emails)
import re
email = "user@[Link]"
pattern = r"^[\w\.-]+@[\w\.-]+\.\w+$"
89
if [Link](pattern, email):
print("Valid Email")
else:
print("Invalid Email")
import re
mobile = "9876543210"
if [Link](r"^[6-9]\d{9}$", mobile):
print("Valid Mobile Number")
else:
print("Invalid Mobile Number")
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")
import re
username = "user_01"
90
if [Link](r"^[a-zA-Z0-9_]+$", username):
print("Valid Username")
else:
print("Invalid Username")
import re
print(new_text)
Real-World Applications
Form validation
Log file analysis
Network monitoring
Data cleaning
Web scraping
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 means collecting data automatically from websites using Python.
Python fetches
Python extracts
Python stores data
Real-World Uses
Libraries Used
Python libraries: requests (fetch HTML), BeautifulSoup (parse HTML), selenium (simulate browser).
import requests
url = "[Link]
response = [Link](url)
92
soup = BeautifulSoup([Link], "[Link]")
print([Link])
What is a Chatbot?
if [Link]() == "hi":
print("Bot: Hello!")
elif [Link]() == "bye":
print("Bot: Goodbye!")
else:
print("Bot: I don't understand")
93
Real-World Uses
Google Translate
Multilingual apps
Chatbots with multiple languages
translator = Translator()
result = [Link]("Hello", dest="ta")
print([Link])
Real-World Uses
Plagiarism checking
Resume matching
Chatbot intent detection
Document comparison
94
Output
Similarity: 0.88
(Keyword Extraction)
What is it?
Real-World Uses
Search engines
Resume screening
Chatbots
95
3. Remaining words are keywords
print("Keywords:", keywords)
words = [Link]()
freq = {}
for w in words:
freq[w] = [Link](w, 0) + 1
print(freq)
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
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)
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)
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)
What is QR Code?
Real-World Uses
Payment apps
Event tickets
Website links
Install Library
pip install qrcode
data = "[Link]
img = [Link](data)
[Link]("python_qr.png")
4️Spell Checker
98
What is Spell Checker?
Real-World Uses
Word processors
Chat applications
Email clients
Install Library
pip install textblob
print([Link]())
word = Word("progrmming")
print([Link]())
5️Scraping Wikipedia
99
What is Web Scraping?
Real-World Uses
Research
Data collection
Automation
print([Link]("Artificial Intelligence"))
page = [Link]("Python")
print([Link])
6️Anagram Program
What is Anagram?
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")
if sorted([Link]()) == sorted([Link]()):
print("Anagram")
print(sorted(s1) == sorted(s2))
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]")
img = [Link]("my_screen.png")
[Link](5)
[Link]("delay_screen.png")
Python has built-in libraries like socket that allow you to create networking applications.
102
Example: Simple TCP Server
import socket
Server-Client Program
-------------------------------------------------------------------------------------------------------------------------------
Introduction to Django
Django follows the MVC pattern (Model-View-Controller), but in Django it’s often called MTV
(Model-Template-View).
103
Django and Python
Views in Django
A view is a Python function or class that receives a request and returns a response.
Example:
def hello(request):
return HttpResponse("Hello, Django!")
104
Example View Rendering Template
from [Link] import render
def hello(request):
return render(request, "[Link]", {"name": "Alice"})
Example:
from [Link] import HttpResponse
def hello(request):
return HttpResponse("<h1>Hello, Django!</h1>")
When you visit /hello/, the browser shows “Hello, Django!” directly.
105
3. Rendering Templates in Views
Example View:
from [Link] import render
def hello(request):
context = {"name": "Alice"} # data for template
return render(request, "[Link]", context)
2. Create an app:
urlpatterns = [
path("hello/", [Link]),
]
106
Static Files in Django
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.
myproject/
myapp/
static/
myapp/
[Link]
[Link]
templates/
[Link]
2. Adding CSS
css
body {
background-color: #f0f0f0;
font-family: Arial, sans-serif;
}
h1 {
color: blue;
}
{% 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
{% load static %}
<img src="{% static 'myapp/[Link]' %}" alt="Logo" width="200">
{% load static %}
<a href="{% url 'about' %}">About Us</a>
5. [Link] Example
urlpatterns = [
path("", [Link], name="home"),
path("about/", [Link], name="about"),
]
-------------------------------------------------------------------------------------------------------------------------------
1. Setup
# myapp/[Link]
from [Link] import models
class Student([Link]):
name = [Link](max_length=50)
grade = [Link](max_length=5)
Run migrations:
3. CRUD Operations
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!")
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'
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!")
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