Python Programming
Chapter-1
Informal Introduction to Programming
What is Programming?
Programming is the process of giving instructions to a computer to perform tasks.
Think of it like:
A recipe → instructions for cooking
A program → instructions for a computer
A program tells the computer:
What to do
How to do it
When to stop
Key Components of Programming
Input → Data given to program
Process → Logic applied to data
Output → Result produced
Example:
Input: 2, 3
Process: Add numbers
Output: 5
What is a Programming Language?
A programming language is a way to communicate with a computer.
Examples:
Python
1
Python Programming
C++
Java
JavaScript
Python is popular because it is:
Easy to read
Beginner-friendly
Very powerful
he process of writing code in Python to solve problems, automate tasks, or build
applications.
💡Simple Definition
Python is a high-level, interpreted programming language that is:
Easy to read and write
Beginner-friendly
Very powerful
💡How Python Programming Works
A Python program follows:
Input → Processing → Output
Example:
a = 5
b = 3
print(a + b)
Input → 5, 3
Processing → addition
Output → 8
2
Python Programming
💡 Why Python is Used
Python is popular because:
Simple syntax (like English)
Less code compared to other languages
Large community and libraries
Features of Python
Python is popular because of its powerful and user-friendly features.
1. Simple and Easy to Learn
Python syntax is very simple and readable, almost like English.
print("Hello World")
�No complex syntax → best for beginners
2. Interpreted Language
Python is interpreted, not compiled.
Code runs line by line
Errors are shown immediately
�Makes debugging easier
3
Python Programming
3. High-Level Language
Python is high-level, meaning:
You don’t need to manage memory manually
Focus is on logic, not hardware details
4. Dynamically Typed
No need to declare data types:
x = 10
x = "Hello"
�Type is decided at runtime
5. Object-Oriented
Python supports OOP concepts:
Classes
Objects
Inheritance
Polymorphism
class Student:
pass
6. Platform Independent (Portable)
Python runs on:
Windows
macOS
4
Python Programming
Linux
�Write once, run anywhere
7. Large Standard Library
Python has a huge built-in library:
Math operations
File handling
Networking
Databases
Example:
import math
print([Link](16))
8. Open Source
Free to use
Source code is publicly available
Large community support
9. Extensible and Embeddable
Can be combined with C, C++
Can be embedded in other applications
10. Supports Multiple Programming
Paradigms
5
Python Programming
Python supports:
Procedural
Object-Oriented
Functional programming
11. Automatic Memory Management
Uses Garbage Collection
Automatically frees unused memory
12. Large Community Support
Millions of developers
Lots of tutorials, libraries, tools
13. Wide Range of Applications
Python is used in:
Web development
AI & Machine Learning
Data Science
Automation
Game development
2. Introduction to Algorithms
What is an Algorithm?
6
Python Programming
An algorithm is a step-by-step procedure to solve a problem.
Example (Making Tea Algorithm):
1. Boil water
2. Add tea leaves
3. Add sugar
4. Add milk
5. Serve
Properties of an Algorithm
Finite (must end)
Clear steps
Well-defined inputs and outputs
Example Algorithm (Add Two Numbers)
1. Start
2. Take input A and B
3. Compute sum = A + B
4. Display sum
5. Stop
Why Algorithms Matter
Help solve problems efficiently
Make programs faster and cleaner
Foundation of all software systems
7
Python Programming
3. Introduction to Data Structures
What is a Data Structure?
A data structure is a way to store and organize data so it can be used
efficiently.
ommon Data Structures
1. List (Array)
Stores multiple values in order.
numbers = [1, 2, 3, 4]
2. Stack (LIFO)
Last In First Out
Like a stack of plates.
3. Queue (FIFO)
First In First Out
Like a line at a ticket counter.
4. Dictionary (Key-Value)
student = {"name": "Rahul", "age": 20}
Why Data Structures Matter
Improve efficiency
Help manage large data
8
Python Programming
Critical for real-world applications
4. Downloading and Installing Python
Step 1: Download Python
Go to:
�[Link]
Click Download Python
Choose latest version (Python 3.x)
Step 2: Install Python
On Windows:
1. Run installer
2. IMPORTANT: ✔ Check "Add Python to PATH"
3. Click Install
On macOS:
Install via .pkg file or use Homebrew:
brew install python
On Linux:
Usually pre-installed, or:
sudo apt install python3
Step 3: Verify Installation
9
Python Programming
Open terminal/command prompt:
python --version
or
python3 --version
You should see something like:
Python 3.x.x
5. Python Interpreter
What is the Python Interpreter?
It executes Python code line by line.
How to Start Interpreter
Open terminal and type:
python
You’ll see:
>>>
This is the Python prompt.
Try Simple Commands
>>> 2 + 3
5
10
Python Programming
>>> print("Hello World")
Hello World
6. Writing and Running a Simple
Python Program
Method 1: Using Interpreter
Just type directly:
>>> print("Hello, Python!")
Method 2: Using a Script File
Step 1: Create File
Create a file:
[Link]
Step 2: Write Code
print("Hello, Python!")
Step 3: Run Program
In terminal:
python [Link]
Output:
Hello, Python!
7. Basic Python Concepts
11
Python Programming
Variables
x = 10
name = "Aman"
Data Types
Integer → 10
Float → 3.14
String → "Hello"
Boolean → True / False
Input from User
name = input("Enter your name: ")
print("Hello", name)
Conditional Statements
age = 18
if age >= 18:
print("Adult")
else:
print("Minor")
Loops
For Loop
for i in range(5):
print(i)
12
Python Programming
While Loop
i=0
while i < 5:
print(i)
i += 1
13
Python Programming
Chapter -2
Variables
What is a Variable?
A variable is a named storage location for data.
x = 10
name = "Riya"
x stores an integer
name stores a string
Rules for Naming Variables
Must start with a letter or _
Cannot start with a number
Case-sensitive (age ≠ Age)
Cannot use keywords (if, for, etc.)
Dynamic Typing (Python Feature)
You don’t declare type explicitly:
x = 10
x = "hello" # valid
2. Operations (Operators)
14
Python Programming
Arithmetic Operators
a = 10
b = 3
a + b # 13
a - b # 7
a * b # 30
a / b # 3.33
a // b # 3 (floor division)
a % b # 1 (remainder)
a ** b # 1000 (power)
Comparison Operators
a == b
a != b
a > b
a < b
a >= b
a <= b
Logical Operators
True and False
True or False
not True
Assignment Operators
x = 5
x += 2 # x = x + 2
x -= 1
x *= 3
3. Control Flow
Control flow determines how code executes.
15
Python Programming
3.1 Conditional Statements
if Statement
age = 18
if age >= 18:
print("Adult")
if-else
if age >= 18:
print("Adult")
else:
print("Minor")
if-elif-else
marks = 75
if marks >= 90:
print("A")
elif marks >= 70:
print("B")
else:
print("C")
3.2 Loops
for Loop
Used when number of iterations is known.
for i in range(5):
print(i)
16
Python Programming
while Loop
Runs while condition is true.
i = 0
while i < 5:
print(i)
i += 1
Loop Control Statements
break # exit loop
continue # skip iteration
pass # do nothing
4. Functions
What is a Function?
A function is a reusable block of code.
Defining a Function
def greet():
print("Hello")
Function with Parameters
def add(a, b):
return a + b
Calling Function
result = add(2, 3)
17
Python Programming
4.1 Default Arguments
def greet(name="Guest"):
print("Hello", name)
greet() # Hello Guest
greet("Aman") # Hello Aman
4.2 Optional Arguments (Keyword Arguments)
def display(name, age):
print(name, age)
display(age=20, name="Riya")
4.3 Variable-Length Arguments
*args (non-keyword)
def add(*numbers):
return sum(numbers)
add(1, 2, 3, 4)
**kwargs (keyword arguments)
def info(**data):
print(data)
info(name="Aman", age=21)
4.4 Passing Functions as Arguments
Functions are first-class objects in Python.
def square(x):
return x * x
18
Python Programming
def apply(func, value):
return func(value)
apply(square, 5)
5. Statements vs Expressions
Statement
A statement performs an action.
x = 10
print(x)
Expression
An expression returns a value.
2 + 3
x * 5
Key Difference
Expression → produces value
Statement → performs action
6. Strings
What is a String?
A sequence of characters.
text = "Hello"
19
Python Programming
6.1 String Operations
a = "Hello"
b = "World"
a + b # concatenation
a * 3 # repetition
a[0] # 'H'
6.2 String Methods
[Link]()
[Link]()
[Link]()
[Link]("H", "J")
[Link]()
6.3 String Formatting
f-strings (recommended)
name = "Riya"
age = 20
print(f"My name is {name}, age {age}")
7. String Processing
Iterating Through String
for ch in "Hello":
print(ch)
Checking Substrings
"ell" in "Hello" # True
Slicing
20
Python Programming
text = "Python"
text[0:3] # 'Pyt'
text[::-1] # reverse
8. Exception Handling
What is an Exception?
An error that occurs during execution.
try-except
try:
x = int("abc")
except ValueError:
print("Conversion failed")
Multiple Exceptions
try:
a = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero")
else and finally
try:
x = 10 / 2
except:
print("Error")
else:
print("Success")
finally:
print("Always runs")
21
Python Programming
9. Basic Input/Output
Input
name = input("Enter name: ")
Output
print("Hello", name)
Type Conversion
age = int(input("Enter age: "))
10. File Handling
Opening a File
file = open("[Link]", "r")
Modes:
"r" → read
"w" → write (overwrite)
"a" → append
"b" → binary
Reading File
[Link]()
[Link]()
[Link]()
22
Python Programming
Writing File
file = open("[Link]", "w")
[Link]("Hello World")
Closing File
[Link]()
10.1 Best Practice (with statement)
with open("[Link]", "r") as file:
content = [Link]()
Automatically closes file
Safer
11. Putting It All Together
A small program using everything:
def process_file(filename="[Link]"):
try:
with open(filename, "r") as f:
content = [Link]()
print([Link]())
except FileNotFoundError:
print("File not found")
process_file()
23
Python Programming
Chapter -3
Class and Object
1.1 What is a Class?
A class is a blueprint for creating objects.
Defines properties (variables)
Defines behaviors (methods)
class Student:
pass
1.2 What is an Object?
An object is an instance of a class.
s1 = Student()
1.3 Class with Attributes and Methods
class Student:
def __init__(self, name, age):
[Link] = name
[Link] = age
def display(self):
print([Link], [Link])
s1 = Student("Riya", 20)
[Link]()
Key Concepts
1. Constructor (__init__)
24
Python Programming
Automatically called when object is created
Initializes object
2. self
Refers to current object
Must be first parameter in methods
1.4 Instance vs Class Variables
class Student:
school = "ABC School" # class variable
def __init__(self, name):
[Link] = name # instance variable
1.5 Encapsulation (Basic Idea)
Restrict access to data.
class Bank:
def __init__(self):
self.__balance = 0 # private variable
2. Data Structures in Python
Data structures help store and organize data efficiently.
25
Python Programming
3. List
3.1 What is a List?
A list is an ordered, mutable collection.
numbers = [1, 2, 3, 4]
3.2 Features
Ordered
Mutable (can change)
Allows duplicates
Can store mixed types
3.3 Accessing Elements
numbers[0]
numbers[-1]
3.4 List Operations
[Link](5)
[Link](1, 10)
[Link](3)
[Link]()
3.5 Slicing
numbers[1:3]
numbers[::-1]
3.6 Iteration
for n in numbers:
print(n)
26
Python Programming
4. Tuple
4.1 What is a Tuple?
A tuple is an ordered, immutable collection.
t = (1, 2, 3)
4.2 Features
Ordered
Immutable (cannot change)
Faster than lists
Allows duplicates
4.3 Accessing Elements
t[0]
4.4 Tuple Packing & Unpacking
t = (1, 2, 3)
a, b, c = t
4.5 When to Use Tuple?
When data should not change
For fixed collections (e.g., coordinates)
5. Sequences
27
Python Programming
5.1 What is a Sequence?
A sequence is an ordered collection.
Examples:
List
Tuple
String
5.2 Common Operations
len(seq)
seq[0]
seq[1:3]
5.3 Membership
3 in [1, 2, 3] # True
5.4 Iteration
for item in seq:
print(item)
6. Set
6.1 What is a Set?
A set is an unordered collection of unique elements.
s = {1, 2, 3}
6.2 Features
Unordered
28
Python Programming
No duplicates
Mutable
Fast membership testing
6.3 Set Operations
[Link](4)
[Link](2)
6.4 Mathematical Operations
a = {1, 2, 3}
b = {3, 4, 5}
a | b # union
a & b # intersection
a - b # difference
6.5 Use Cases
Remove duplicates
Membership testing
Mathematical set operations
7. Dictionary
7.1 What is a Dictionary?
A dictionary stores data in key-value pairs.
student = {
"name": "Riya",
"age": 20
}
29
Python Programming
7.2 Features
Unordered (in concept)
Mutable
Keys must be unique
Fast lookup
7.3 Accessing Values
student["name"]
7.4 Adding/Updating
student["age"] = 21
student["city"] = "Mumbai"
7.5 Removing Items
[Link]("age")
7.6 Iteration
for key, value in [Link]():
print(key, value)
7.7 Dictionary Methods
[Link]()
[Link]()
[Link]()
30
Python Programming
Combined Example
class Student:
def __init__(self, name, marks):
[Link] = name
[Link] = marks
students = [
Student("Aman", [80, 90]),
Student("Riya", [85, 95])
]
for s in students:
print([Link], sum([Link]))
31
Python Programming
Key Differences Explained
1. Mutability
List, Set, Dictionary → can change
Tuple → cannot change
2. Order
List & Tuple → maintain order
Set → no order
Dictionary → ordered (Python 3.7+)
3. Access Method
List/Tuple → index ([0])
Set → no indexing
Dictionary → key (["name"])
4. Duplicates
List/Tuple → allowed
Set → removed automatically
Dictionary → keys must be unique
💡Simple Analogy
List → Shopping list (can add/remove items)
32
Python Programming
Tuple → Fixed menu (cannot change)
Set → Unique items collection (no repeats)
Dictionary → Phone book (name → number)
💡Small Combined Example
data = [1, 2, 2, 3]
print(list(data)) # List
print(tuple(data)) # Tuple
print(set(data)) # Set removes duplicates
d = {"a": 1, "b": 2}
print(d["a"]) # Dictionary access
33
Python Programming
Chapter-4
Here are clear, structured, and in-depth notes on:
Databases & SQL
SQLite & SQLite Manager
Spidering Twitter (concept + database use)
Multiple tables & JOIN
1. Introduction to Databases
What is a Database?
A database is an organized collection of data stored
electronically.
Example:
Student records
Banking systems
Social media data
Why Use Databases?
Store large data efficiently
Fast retrieval
Data consistency
Multi-user access
34
Python Programming
2. Structured Query
Language (SQL)
What is SQL?
SQL (Structured Query Language) is used to:
Store data
Retrieve data
Update/delete data
2.1 Basic SQL Commands
1. CREATE TABLE
CREATE TABLE students (
id INTEGER PRIMARY KEY,
name TEXT,
age INTEGER
);
2. INSERT
INSERT INTO students (name, age)
VALUES ('Riya', 20);
3. SELECT
SELECT * FROM students;
35
Python Programming
4. UPDATE
UPDATE students
SET age = 21
WHERE name = 'Riya';
5. DELETE
DELETE FROM students
WHERE name = 'Riya';
3. SQLite
What is SQLite?
SQLite is a lightweight, file-based database.
No server needed
Stored in a single file (.db)
Built into Python
3.1 Using SQLite in Python
import sqlite3
conn = [Link]("[Link]")
cur = [Link]()
[Link]("CREATE TABLE IF NOT EXISTS users (name
TEXT, age INTEGER)")
[Link]("INSERT INTO users VALUES ('Aman', 21)")
36
Python Programming
[Link]()
[Link]()
4. SQLite Manager
What is SQLite Manager?
A GUI tool to:
Create databases
Run SQL queries
View tables
Examples:
DB Browser for SQLite
SQLiteStudio
Basic Workflow
1. Create database
2. Create table
3. Insert data
4. Run queries
5. View results
37
Python Programming
5. Spidering Twitter Using a
Database
What is Spidering?
Spidering = collecting data from websites automatically.
Twitter Spidering Concept
Fetch data (tweets, users, followers)
Store in database
Analyze relationships
Example Data to Store
User ID
Username
Followers
Tweets
Simple Python Concept (Pseudo Example)
import sqlite3
conn = [Link]("[Link]")
cur = [Link]()
[Link]("CREATE TABLE IF NOT EXISTS users (name
38
Python Programming
TEXT, followers INTEGER)")
# Example data (instead of real API)
[Link]("INSERT INTO users VALUES ('user1', 100)")
[Link]()
Why Use Database Here?
Avoid duplicate data
Track relationships
Efficient queries
6. Programming with
Multiple Tables
Why Multiple Tables?
To:
Reduce redundancy
Organize data
Maintain relationships
Example Tables
Users Table
CREATE TABLE users (
id INTEGER PRIMARY KEY,
39
Python Programming
name TEXT
);
Tweets Table
CREATE TABLE tweets (
id INTEGER PRIMARY KEY,
user_id INTEGER,
content TEXT
);
Relationship
One user → many tweets
Linked using user_id
7. JOIN (Important Concept)
What is JOIN?
JOIN combines data from multiple tables.
7.1 INNER JOIN
Returns matching rows from both tables.
SELECT [Link], [Link]
FROM users
JOIN tweets
ON [Link] = tweets.user_id;
40
Python Programming
7.2 LEFT JOIN
Returns all from left + matched from right.
SELECT [Link], [Link]
FROM users
LEFT JOIN tweets
ON [Link] = tweets.user_id;
7.3 RIGHT JOIN (Not supported in SQLite)
Use LEFT JOIN instead.
7.4 Example Output
name content
Riya Hello World
Aman Learning SQL
8. Real-Life Example
(Twitter-like System)
Tables:
Users
Followers
Tweets
41
Python Programming
Followers Table
CREATE TABLE followers (
user_id INTEGER,
follower_id INTEGER
);
Query Example (Find followers)
SELECT [Link]
FROM users
JOIN followers
ON [Link] = followers.follower_id;
9. Key Concepts Summary
Database
Stores structured data
SQL
Language to interact with database
SQLite
Lightweight database
Spidering
Collecting web data into database
42
Python Programming
Multiple Tables
Organize related data
JOIN
Combine tables using relationships
Using Databases in Python (SQLite)
Python has a built-in module:
import sqlite3
1.1 Connecting to a Database
import sqlite3
conn = [Link]("[Link]") # creates or opens DB
cur = [Link]() # cursor to execute SQL
1.2 Creating a Table
[Link]("""
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT,
age INTEGER
)
""")
43
Python Programming
1.3 Inserting Data
[Link]("INSERT INTO users (name, age) VALUES (?, ?)",
("Aman", 21))
[Link]()
�? prevents SQL injection (very important)
1.4 Fetching Data
[Link]("SELECT * FROM users")
rows = [Link]()
for row in rows:
print(row)
1.5 Closing Connection
[Link]()
2. Full Example (CRUD in Python)
import sqlite3
conn = [Link]("[Link]")
cur = [Link]()
[Link]("CREATE TABLE IF NOT EXISTS students (name TEXT,
marks INTEGER)")
44
Python Programming
[Link]("INSERT INTO students VALUES (?, ?)", ("Riya", 90))
[Link]("SELECT * FROM students")
print([Link]())
[Link]()
[Link]()
3. Spidering Twitter Using Python +
Database
3.1 Concept
Spidering =
�Fetch data → Store in database → Expand network
3.2 Database Design
[Link]("""
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
username TEXT UNIQUE
)
""")
[Link]("""
45
Python Programming
CREATE TABLE IF NOT EXISTS follows (
from_id INTEGER,
to_id INTEGER
)
""")
3.3 Inserting Without Duplicates
[Link]("INSERT OR IGNORE INTO users (username) VALUES (?)",
(name,))
3.4 Simulating Spidering
users = ["aman", "riya", "john"]
for u in users:
[Link]("INSERT OR IGNORE INTO users (username) VALUES
(?)", (u,))
[Link]()
3.5 Creating Relationships
[Link]("INSERT INTO follows (from_id, to_id) VALUES (1,
2)")
4. Working with Multiple Tables in
Python
46
Python Programming
4.1 Creating Tables
[Link]("""
CREATE TABLE users (
id INTEGER PRIMARY KEY,
name TEXT
)
""")
[Link]("""
CREATE TABLE tweets (
id INTEGER PRIMARY KEY,
user_id INTEGER,
content TEXT
)
""")
4.2 Inserting Data
[Link]("INSERT INTO users VALUES (1, 'Aman')")
[Link]("INSERT INTO tweets VALUES (1, 1, 'Hello World')")
5. JOIN in Python (Very Important)
5.1 INNER JOIN
[Link]("""
SELECT [Link], [Link]
FROM users
JOIN tweets
ON [Link] = tweets.user_id
47
Python Programming
""")
for row in [Link]():
print(row)
Output
('Aman', 'Hello World')
5.2 LEFT JOIN
[Link]("""
SELECT [Link], [Link]
FROM users
LEFT JOIN tweets
ON [Link] = tweets.user_id
""")
48
Python Programming
49