Pyhton Textbook Akarsh
Pyhton Textbook Akarsh
Blood
─
1
💡
Analogy:
Think of a robot that you want to cook noodles. You cannot just say,“Make Maggi!”. You
must give step-by-step instructions:
Notes:
Exercise 1.1
3. Do you notice how these instructions resemble programming steps?
● G
eneral-purpose→ you can use it in almost every domain(web, AI, data science,
automation, etc.).
💡Analogy:
Fun Fact:
ython isnot named after the snake!🐍 It comes froma British comedy show“Monty
P
Python’s Flying Circus”.
Exercise 1.2
2. Compare Python with at least one other programming language (C, Java, etc.).
4
Key Reasons
💡
Analogy:
Imagine a Swiss Army knife 🗡️. It can act as a knife, screwdriver, bottle opener, and more.
Python is that multi-purpose tool for programmers.
Pitfall:
ecause Python looks easy, beginners often underestimate it. But mastering it deeply can
B
take years.
5
Exercise 1.3
● 2000→ Python 2.0 released with major features (Unicode,garbage collection).
● 2008→ Python 3.0 released. Cleaner, modern, but notbackward compatible.
Fun Fact:
uido van Rossum was humorously called the“BenevolentDictator For Life (BDFL)”
G
because of his central role in guiding Python’s development.
Exercise 1.4
2. What was the biggest reason for creating Python 3?
💡Diagram:
Pitfall:
ython can be slower than C/C++ because it is interpreted. But developer speed often
P
matters more than execution speed.
Exercise 1.5
Steps:
Verify installation:
python --version
3.
● PyCharm(professional).
I am learning Python.
Example:
print("Hello, World!")
10
💡
Why “Hello, World!”?
It’s like saying“Mic check, 1…2…3”before a concert.
Create a script that asks for your name and then prints:
✅ Summary of Chapter 1
12
henever you need something, you don’t search the whole cupboard; you just look at the
W
label.
● You don’t need to know theexact addressin memory— you just use the label.
Example:
age = 21
name = "Akarsh"
pi = 3.14159
Notes:
Pitfall:
Exercise 2.1
2.
✅ Allowed:
● Underscore
_
❌ Not Allowed:
Examples:
valid_name = "Rahul"
_name123 = "Python"
rollNumber = 45
❌ Invalid:
123name = "wrong"
my-name = "wrong"
Exercise 2.2
1.
2cool
2.
cool2
3.
_hidden
16
4.
break
5.
my name
age = 25
temperature = -5
1.
pi = 3.14
height = 1.82
2.
name = "Python"
3.
is_student = True
is_coder = False
17
4.
Fun Fact:
Python automatically figures out the type. Unlike Java or C, you don’t have to declare it.
Exercise 2.3
○ Yourage(int)
○ Yourheight(float)
Example:
age = "21"
# string
age_num = int(age)
# convert to int
print(age_num + 1)
# Output: 22
Conversion Functions:
int()→ to integer
●
float()→ to float
●
str()→ to string
●
bool()→ to boolean
●
Pitfall:
int("hello")
# ❌ Error
Exercise 2.4
1. Convert
"3.14"(string) into a float.
2. Convert
1into a boolean.
3. Convert
Trueinto an integer.
19
Types of Operators
+addition
○
-subtraction
○
*multiplication
○
/division
○
%modulus (remainder)
○
**exponentiation
○
//floor division
○
print(5 + 2)
# 7
print(5 % 2)
# 1
print(2 ** 3)
# 8
2.
==equal
○
!=not equal
○
20
>greater than
○
<less than
○
>=greater or equal
○
<=less or equal
○
print(5 > 2)
# True
print(5 == 2)
# False
3.
print(True or False)
# True
print(not True)
# False
4.
=assignment
○
○ ,
+= ,
-= ,
*= /=etc. (update shorthand)
21
x = 5
x += 2
# x = x + 2
print(x) # 7
5.
○ ,
in not in
print("apple" in fruits)
# True
6.
○ ,
is is not
x = [1, 2, 3]
y = x
print(x is y)
# True (same object)
print(x is not y)
# False
7.
Exercise 2.5
22
✅ Chapter 2 Summary
● Variables arenamed containersfor data.
● N
aming rules: can use letters, numbers, underscore (but no spaces, special symbols,
or keywords).
Real-Life Analogy
1. Jump
2. Run
3. Hide
if action == "jump":
else:
Comparison Operators
==
Equal to == 5→
5
True
!=
Not equal to != 3→
5
True
>
Greater than 7 > 4→ True
<
Less than 3 < 9→ True
>=
Greater or equal >= 5→
5
True
<=
Less or equal <= 3→
2
True
Logical Operators
and
Both True 5>2 and 3<4)→
(
True
or
Any one True 5>2 or 3>4)→
(
True
not
Reverse True/False not(5>2)→ False
1. Ask the user for a number. Print whether it ispositive,negative, or zero.
5. Ask for username → if correct → print welcome, else → “Try again”.
Example 3.2
marks = 85
attendance = 90
26
else:
else:
● Marks ≥75 and attendance <80 → passed but low attendance
○ If age > 18 → Check temperature: >30 Hot, else Pleasant
○ Correct PIN → check balance → if balance >0 print “Active”, else “Overdrawn”
word = "Python"
print(letter)
Output:
P
y
t
h
o
n
print(i)
Output: 2, 4, 6, 8, 10
print(f"i={i}, j={j}")
Output:
i=1, j=1
i=1, j=2
...
i=3, j=3
*
**
***
****
i = 1
print(i)
i += 1
while True:
if user_input == "exit":
break
# Break example
if i % 7 == 0:
break
# Continue example
if i % 2 == 0:
continue
print(i)
# Pass example
if i == 3:
pass
print(i)
31
guess = 0
attempts = 0
attempts += 1
print("Too low!")
print("Too high!")
else:
32
✅Chapter 3 Summary
Analogy:
Imagine you have ajuice machine. You put fruits in→ it gives juice. You don’t need to
manually squeeze every time.
def greet():
print("Hello, brother!")
greet()
# Calling the function
34
Output:
Hello, brother!
def greet(name):
print(f"Hello, {name}!")
greet("Akarsh")
greet("Python Legend")
Output:
Hello, Akarsh!
name→parameter
●
"Akarsh"→argument
●
return a + b
print(result)
Output:
12
Type Example
2. Write a function that adds two numbers and prints the result.
3. Write a function that takes temperature in Celsius and returns Fahrenheit.
5. Create a function that says “Good Morning” based on the time of day.
Default Values
def greet(name="Brother"):
print(f"Hello, {name}!")
greet()
# Hello, Brother!
greet("Akarsh")
# Hello, Akarsh!
Keyword Arguments
describe(age=20, name="Akarsh")
Output:
x = 10
# global
def show():
y = 5
# local
print(x, y)
show()
print(x)
square = lambda x: x ** 2
38
print(square(5))
# 25
add = lambda a, b: a + b
print(add(10, 15))
# 25
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n-1)
print(factorial(5))
# 120
return a + b
return a - b
return a * b
if b != 0:
return a / b
else:
while True:
if choice == "exit":
break
if choice == "add":
print(add(x, y))
print(subtract(x, y))
print(multiply(x, y))
print(divide(x, y))
else:
print("Invalid choice!")
✅Chapter 4 Summary
● Syntax:
print(my_list)
Output:
43
List Operations
Slicing my_list[1:4]
[20,30,'Python']
Length len(my_list)
6
● Syntax:
print(my_tuple)
Tuple Operations
● Syntax:
print(my_set)
Output:
Set Operations
● Syntax:
print(my_dict)
47
Output:
Dictionary Operations
Keys my_dict.keys()
dict_keys([...])
Items my_dict.items()
dict_items([...])
1. Create a dictionary with your favorite movies and their release years.
data = {
"students": [
]
}
print(data["students"][1]["name"])
# Python Legend
● Features:
students = {}
49
def remove_student(name):
[Link](name, None)
if name in students:
students[name]["marks"] = marks
def show_students():
print(name, info)
# Example Usage
update_marks("Akarsh", 97)
show_students()
remove_student("Python Legend")
show_students()
50
✅Chapter 5 Summary
● S
trings areimmutable, which means you cannot changeindividual characters
directly.
● Syntax:
print(text)
Output:
52
Hello, Python!
● S
trings can be insingle quotes , double quotes
' ' , or triple quotes
" " ''' '''
/
""" """for multi-line strings.
text = "Python"
print(text[0])
# P
53
● Slicing:
text[start:end:step]
text = "PythonProgramming"
print(text[0:6])
# Python
print(text[6:])
# Programming
print(text[::2])
# Pto rgamn (every 2nd char)
54
Repetition "Hi"*3
HiHiHi
Character Meaning
\n
New line
\t
Tab
56
\\
Backslash
\'
Single quote
\"
Double quote
text = "
Python is Awesome! "
print([Link]())
# PYTHON IS AWESOME!
57
print([Link]())
# python is awesome!
print([Link]())
# removes spaces from start and end
print([Link]("Awesome", "Legendary"))
# Python is Legendary!
print([Link]())
# ['Python', 'is', 'Awesome!']
2. Slice
"PythonRocks"to get only .
"Rocks"
4. Replace
"Good"with .
"Legendary"
age = 20
Output:
It is powerful
It is easy to learn"""
print(multi_line)
61
Output:
This is Python
It is powerful
It is easy to learn
text = "Python"
print(text[::-1])
# nohtyP
word = "level"
if word == word[::-1]:
print("Palindrome")
63
else:
print("Not Palindrome")
2. Convert
"python legend"to title case ( ).
Python Legend
3. Split
"Python is amazing"into a list of words.
4. Join
["Python", "is", "awesome"]into a single string.
● Output:
# Number of characters
chars = len(text)
# Number of words
words = len([Link]())
67
# Number of sentences
# Count vowels
vowels = 'aeiouAEIOU'
print(f"Characters: {chars}")
print(f"Words: {words}")
print(f"Sentences: {sentences}")
✅Chapter 6 Summary
69
7.1 Introduction
● Python programs often need tomake decisionsorrepeatactions.
Think of it like:
" If it’s raining, take umbrella, else enjoy the sun." 🌦️
"Do push-ups 10 times, repeat daily." 💪
Syntax:
if condition1:
71
# do something
elif condition2:
# do something else
else:
# default action
else:
Logical Operators
73
● ,
and ,
or notfor complex conditions:
x = 10
y = 5
○ 90-100 → A
○ 75-89 → B
○ 50-74 → C
○ <50 → F
1.
forloop→ iterate over a sequence (list, string,range).
2.
whileloop→ repeatwhile a condition is True.
7.3.1
forLoop
75
print(i)
word = "Python"
print(letter)
7.3.2
whileLoop
# Example: Counting down
count = 5
77
print(count)
count -= 1
i = 0
78
print(i)
i += 1
break
Exit the loop immediately Stop on certain condition
continue
Skip current iteration, continue next Skip even numbers etc.
pass
Do nothing placeholder Placeholder for code
if i == 5:
break
# stops the loop
print(i)
80
if i == 3:
continue
# skips 3
print(i)
print(i*j, end="\t")
print()
*
**
***
83
****
****
***
**
*
84
import random
guess = None
85
print("Too low!")
print("Too high!")
86
else:
8.1 Introduction
● Functions arereusable blocks of code.
hink of it like:
T
“I don’t want to wash my hands every time separately,let’s build a machine
(function) and use it whenever.”🧼
Syntax
def function_name(parameters):
88
# code block
return value
greet()
● Output:
Hello, Brother! Welcome to Python!
greet_user("Akarsh")
● Output:
Hello, Akarsh! Welcome to Python!
return a + b
print("Sum:", result)
● Output:
Sum: 8
print(square(5))
# Output: 25
greet("Akarsh", 20)
def greet(name="Brother"):
print(f"Hello, {name}!")
greet()
# Hello, Brother!
greet("Akarsh")
# Hello, Akarsh!
return sum(args)
print(add_numbers(1, 2, 3, 4))
# Output: 10
def show_info(**kwargs):
show_info(name="Akarsh", age=20)
x = 10
# global
97
def func():
y = 5
# local
print("Inside:", x + y)
func()
print("Outside:", x)
# y is not accessible
98
def factorial(n):
if n == 0 or n == 1:
return 1
else:
return n * factorial(n-1)
99
print(factorial(5))
# Output: 120
return a + b
return a - b
101
return a * b
if b != 0:
return a / b
else:
102
if choice == "add":
print(add(num1, num2))
print(subtract(num1, num2))
print(multiply(num1, num2))
104
print(divide(num1, num2))
else:
print("Invalid choice")
9.1 Introduction
● Just like functions are used forcode reuse,modulesand packageshelp organize
large programs.
File:
[Link]
def greet(name):
return f"Hello, {name}!"
File:
[Link]
import mymodule
print([Link]("Akarsh"))
print([Link](5, 7))
Output:
Hello, Akarsh!
12
import math
print([Link](16))
import math as m
print([Link](5))
108
Structure:
mypackage/
__init__.py
[Link]
[Link]
Usage:
Folder Structure:
MathTools/
__init__.py
[Link]
[Link]
[Link]
109
[Link]
def area_circle(radius):
import math
return [Link] * radius ** 2
[Link]
print([Link](10, 5))
# 15
print(geometry.area_circle(7))
# 153.938...
Example:
import random
print([Link](1, 100))
# Random number between 1-100
import requests
response = [Link]("[Link]
print(response.status_code)
print([Link]())
9.6 Exercises
111
4. Use
datetimeto print the current date and time
5. Install
requestsand make a request to a public APIlike GitHub
Folder Structure:
MyLibrary/
__init__.py
[Link]
[Link]
[Link]
books = []
def show_books():
for book in books:
print(f"{book['title']} by {book['author']}")
112
[Link]
members = []
def add_member(name):
[Link](name)
def show_members():
for member in members:
print(member)
[Link]
books.show_books()
members.show_members()
Output:
his demonstrates how you canstructure reusable code using modules and
T
packages.
9.8 Summary
● Module:single Python file with reusable functions/classes
10.1 Introduction
● Files are used tostore data permanently.
● Unlike variables which store data temporarily (in memory),files save data on disk.
hink of files asnotebooks. You can write new notes,read existing ones, or
T
add more notes at the end.
Mode Description
'r'
Read (default) – file must exist
'w'
Write – creates file or overwrites
'a'
Append – adds to the end of file
'b'
Binary mode (e.g.,
'rb'or )
'wb'
# Do operations
content = [Link]()
print(content)
10.4 Using
withStatement (Recommended)
with open("[Link]", "r") as file:
content = [Link]()
print(content)
# No need to explicitly close the file
10.9 Exercises
1. Create a file
[Link]and write yourname, age,and favorite language.
4. C
reate afile containing numbers from 1 to 50, thenread it and printonly even
numbers.
5. Read a binary file (image or PDF) and print itssizein bytes.
def add_task(task):
with open("[Link]", "a") as file:
[Link](task + "\n")
def show_tasks():
with open("[Link]", "r") as file:
tasks = [Link]()
for idx, task in enumerate(tasks, 1):
print(f"{idx}. {[Link]()}")
# Demo
add_task("Learn Python Modules")
add_task("Build mini-projects")
print("Your Tasks:")
show_tasks()
Output:
Your Tasks:
1. Learn Python Modules
2. Build mini-projects
119
You cankeep adding tasks, and they will be savedpermanently in .
[Link]
10.11 Summary
● Python files allowpermanent storage of data.
● Use
withforautomatic closing.
11.1 Introduction
● In programming, sometimeserrors occurduring execution.
● P
ython provides away to catch and handle errorsusingtry, except, else, and
finallyblocks.
hink of it likedriving a car: you put a seatbelt,check brakes, and have airbags.
T
Errors might happen, but you can handle them safely.
Exception Meaning
IndexError
Invalid index in a list
KeyError
Key not found in dictionary
ValueError
Wrong type of value (e.g., int("abc"))
TypeError
Wrong operation between types
NameError
Using a variable that does not exist
121
x = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero!")
● Use
raisetoforce an errorif condition is invalid.
pass
11.9 Exercises
1. Write a program todivide two numbers, handle .
ZeroDivisionError
print(safe_divide(10, 2))
print(safe_divide(10, 0))
print(safe_divide(10, "a"))
Output:
5.0
Error: Cannot divide by zero!
Error: Invalid input type!
11.11 Summary
125
12.1 Introduction
● As your Python programs grow,all code in a singlefile becomes messy.
import math
print([Link](16))
# Output: 4.0
print([Link])
# Output: 3.141592653589793
my_module.py
def greet(name):
return f"Hello, {name}!"
[Link]
import my_module
print(my_module.greet("Akarsh"))
print(my_module.add(5, 7))
import random
print([Link](1, 10))
Module Purpose
Example structure:
my_project/
│
├── utils/
│
├── __init__.py
│
├── file_ops.py
│
└── math_ops.py
│
└── [Link]
print(add(5,3))
print(subtract(10,4))
2. Add
__init__.py(can be empty)
math_ops.py
return a + b
[Link]
print(add(5,6))
print(multiply(4,7))
12.8 Exercises
1. C
reate a module[Link]with
add, subtract,
multiply, divide
functions. Import and test it.
2. W
rite a module[Link]with
hello(name)and
goodbye(name)functions.
Use it in another file.
131
3. C
reate a package shapeswith modules
[Link]and . Implement
[Link]
area calculation in both.
4. Use
randommodule to simulate adice roll.
5. Use
datetimemodule to printcurrent date and time.
Structure:
library/
│
├── __init__.py
├── [Link]
# Functions for adding, listing books
└── [Link]
# Functions for managing users
[Link]
# Main program
[Link]
books = []
def add_book(title):
[Link](title)
def list_books():
return books
[Link]
132
users = []
def add_user(name):
[Link](name)
def list_users():
return users
[Link]
add_book("Python Mastery")
add_user("Akarsh")
print(list_books())
print(list_users())
Output:
['Python Mastery']
['Akarsh']
12.10 Summary
133
13.1 Introduction
hen we write a Python program, all the data existsonly in memorywhile the program is
W
running.
Once the program ends, all the memory data disappears.
2. B
inary Files (.bin, .jpg, .png)– contains non-textdata like images, videos, or other
formats
Files are essential for applications like contact books, logs, data storage, and more.
Syntax:
File Modes:
Mode Meaning
13.5 Using
withStatement (Best Practice)
The
withstatement automatically closes the file whendone.
Example:
Method Description
read()
Read the entire file
13.8 Exercises
1. Create a file
[Link]and write names of 5 students.
2. Read
[Link]line by line and print names withline numbers.
[Link]
def list_contacts():
139
[Link]
add_contact("Akarsh", "9876543210")
add_contact("Riya", "9123456789")
list_contacts()
Expected Output:
13.10 Summary
● Files allowpermanent data storage
● U
se file methods: ,
read() ,
readline() ,
readlines() ,
write() ,
writelines()
close()
140
14.1 Introduction
hen you write a Python program, sometimes things don’t go as expected.
W
Errors can happen while your program is running.
Example:
print(10 / num)
e need a way to handle errors gracefully so the program doesn’t crash. This is
W
where Exception Handling comes in.
Exception Cause
ValueError
Invalid data type conversion
IndexError
Invalid index in a list
KeyError
Accessing missing key in dictionary
TypeError
Operation on incompatible types
Syntax:
try:
except ExceptionType:
Example:
try:
print(10 / num)
except ZeroDivisionError:
except ValueError:
try:
result = 10 / num
except ZeroDivisionError:
except ValueError:
print("Invalid input!")
else:
print(f"Result is {result}")
try:
content = [Link]()
except FileNotFoundError:
finally:
class TooYoungError(Exception):
pass
Example:
import logging
[Link](level=[Link])
return a / b
print(divide(10, 0))
# Will raise error
14.9 Exercises
145
1. W
rite a program that asks for a number and prints its reciprocal. Handle
ZeroDivisionErrorand
ValueError .
2. O
pen a file . If it doesn’t exist, print “Filemissing” instead of
[Link]
crashing.
3. W
rite a program that asks for age. If age < 18, raise a custom exception
TooYoungError
.
4. Write a function that divides two numbers. Use logging to print debug info.
5. C
ombine ,
try ,
except , and
else finallyin a programthat reads a file and
prints its content.
[Link]
import logging
[Link](filename="[Link]", level=[Link])
try:
result = a / b
except ZeroDivisionError:
return None
else:
return result
print(f"Result = {res}")
14.11 Summary
● Exceptions are runtime errors that can crash a program
📖 Chapter 15: Python Modules & Packages – Organize Your Code Like
a Pro
Introduction
hen your Python programs get bigger, writing all code in a single file becomes
W
messy.
Imagine building a huge app like Instagram or Flipkart — you cannot put everything
in one file, right?
his is where Modules and Packages come in. They help you organize your code,
T
reuse it, and make it more readable.
What is a Module?
● A module is a Python file containing functions, variables, or classes.
● You can import a module in another Python file to use its content.
Example:
# file: [Link]
def say_hello(name):
print(f"Hello, {name}!")
def say_goodbye(name):
print(f"Goodbye, {name}!")
148
# file: [Link]
import greetings
greetings.say_hello("Akarsh")
greetings.say_goodbye("Akarsh")
✅ Output:
Hello, Akarsh!
Goodbye, Akarsh!
Importing Modules
Python provides multiple ways to import:
import math
print([Link](16))
print(sqrt(25))
print(pow(2, 3))
import math as m
print([Link](5))
Example:
import random
print([Link](1, 100))
# Random number between 1 and 100
150
Creating Packages
● A package is a folder containing multiple modules.
Structure Example:
my_package/
__init__.py
[Link]
math_tools.py
Usage:
greetings.say_hello("Akarsh")
Exploring Modules
● Use
dir()to see contents of a module:
import math
print(dir(math))
● Use
help()to see documentation:
151
import math
help([Link])
Example:
import requests
response = [Link]("[Link]
print(response.status_code)
blog_app/
__init__.py
[Link]
[Link]
# handles user registration & login
[Link]
# handles blog posts
152
[Link]
# helper functions
Exercises
1. C
reate a module [Link]with functions ,
add ,
subtract ,
multiply
divide
. Import it in another file and test all functions.
2. Explore
osmodule: Print current directory, list allfiles, create a new folder.
4. C
reate a packagemy_toolswith two modules:
string_utils.py(string
operations) and
math_utils.py(math operations). Testthem in a separate
file.
Structure:
todo_app/
__init__.py
[Link]
# add, remove, view tasks
[Link]
# program entry point
153
[Link]
tasks = []
def add_task(task):
[Link](task)
def remove_task(task):
if task in tasks:
[Link](task)
def view_tasks():
for t in tasks:
print("-", t)
[Link]
while True:
if action == "add":
add_task(task)
154
remove_task(task)
view_tasks()
break
else:
print("Invalid action")
Summary
● Modules = Python files with reusable code
● Use
importand
from … importto reuse code
● Python has a Standard Library and supports external modules via
pip
● O
rganizing code with modules/packages improves readability, maintainability,
and scalability
155
Real-life analogy:
● Types:
💡
Tip: Always choose database based on your project need. For simple apps →
SQLite/MySQL, for analytics → PostgreSQL/Cassandra, for caching → Redis.
conn = [Link]("[Link]")
cursor = [Link]()
[Link]()
cursor = [Link]()
age INTEGER,
)
""")
[Link]()
UNIQUE→ No duplicates
●
Tip: Always design table schema before coding. Bad schema → nightmares later.
Single Insert
[Link]()
[Link]()
Important Tip:
all_users = [Link]()
print(user)
# Conditional
print([Link]())
[Link]()
# Delete
[Link]()
[Link]()
[Link]()
print("Error:", e)
[Link]("""
FROM orders
""")
Types of joins:
[Link]()
print([Link]())
● Features:
● Features:
● Tables:
tasks
● Features:
3. Design Orders & Customers tables; find top 3 customers by total order amount
16.14 Summary
● Python + databases = full-stack power
● Apps like Netflix, Flipkart, Amazon handle millions of users and requests.
4. Big Data → relational databases can't handle billions of rows easily
NoSQL Advantages
ro Tip: Real-world apps often use hybrid DB → SQL for transactions, NoSQL for
P
analytics and caching.
client = MongoClient("mongodb://localhost:27017/")
db = client["shop"]
collection = db["products"]
# Insert
168
collection.insert_one(product)
# Read
print(p)
Advanced Concepts:
import redis
[Link]('user:1001', 'Akarsh')
print([Link]('user:1001'))
169
Use-Cases:
Pro Tip: Redis supports pub/sub, sorted sets, bitmaps → real-time analytics.
pipeline = [
]
result = list([Link](pipeline))
print(result)
with session.start_transaction():
💡
Tip: Always use transactions for order placement, inventory management,
banking apps
import psycopg2
print([Link]())
● Horizontal scaling: multiple servers → complex, needed for massive apps
Techniques:
2. I mplement Transactional Order System → update stock & create invoice
atomically
7. Hybrid SQL + NoSQL design → for a real-world social media app
17.10 Summary
● Python + Advanced DB = superpower combo
● Netflix ka algorithm decide karta hai what you will watch next
● A
mazon & Flipkart ka backend continuously monitor karta hai price trends,
top-selling products
ython humko scrape, fetch, process, clean, store aur analyze data ka complete
P
superpower deta hai.
hink of Python as your magic wand: you tell it “bring me this data, clean
T
it, store it, and show insights” and it does everything!
requests
Fetch raw HTML content from websites
pandas
Convert scraped data into tables and do transformations
selenium
Automate dynamic pages (JS-heavy websites)
lxml
Faster HTML/XML parsing for big projects
import requests
url = "[Link]
response = [Link](url)
html_content = [Link]
print(html_content[:500])
# Preview first 500 characters
headings = soup.find_all("h2")
for h in headings:
print([Link])
Tip: Use
[Link]()to see HTML structure neatly.
print(link['href'])
base_url = "[Link]
response = [Link](url)
print([Link])
[Link]([Link](2,5))
driver = [Link]()
[Link]("[Link]
for t in titles:
print([Link])
[Link]()
Extra Tips:
● Always
[Link]()to close the browser
What is an API?
import requests
url = "[Link]
data = [Link](url).json()
print(data['bpi']['USD']['rate'])
Tip:
● Read API docs carefully → know endpoints, params, rate limits
import psycopg2
conn = [Link](
database="scraper_db",
user="postgres",
password="pass"
)
cur = [Link]()
# Create table
[Link]("""
180
name VARCHAR(50),
price FLOAT,
)
""")
# Insert data
[Link]()
[Link]()
client = MongoClient("mongodb://localhost:27017/")
db = client["crypto_db"]
collection = db["prices"]
Use Case:
data = [Link]([
])
data = data.drop_duplicates()
data['price'] = data['price'].fillna(data['price'].mean())
print(data)
182
2. Fetch live Bitcoin price every 10 mins → store in SQL → plot last 24 hours trend
3. Scrape e-commerce product → track price drops → send email alerts
4. Scrape IMDb Top 250 → extract name, year, rating → save in CSV + MongoDB
18.10 Summary
● Python allows full-cycle data handling → scrape, API, store, analyze
● SQL & NoSQL = backbone for structured & semi-structured data
Examples:
1. N
etflix → Users ke watch history analyze karke personalized
recommendations
2. A
mazon/Flipkart → Product sales track karke dynamic pricing aur stock
management
3. Banks → Transaction patterns analyze karke fraud detect karte hain
4. G
overnment → Population, healthcare, employment data analyze karke
policies banate hain
Think like: Python = Magic wand for turning raw data into decisions
186
pandas D
ata cleaning, transformation, CSV, Excel, JSON files handle
aggregation
numpy
athematical operations, arrays,
M ast computation, vectorized
F
statistics ops
data = pd.read_csv("sales_data.csv")
print([Link]())
# First 5 rows
print([Link]())
# Columns, types, missing values
print([Link]())
# Statistical summary
data['sales'].fillna(data['sales'].mean(), inplace=True)
# Drop duplicates
data.drop_duplicates(inplace=True)
188
print(top_products[['product_name', 'sales']])
monthly_sales = [Link]('month')['sales'].sum()
print(monthly_sales)
● ,
inner ,
left ,
right outerjoins → SQL jaise operations
● R
ename columns for clarity:
[Link](columns={'old':'new'},
inplace=True)
months = ['Jan','Feb','Mar','Apr']
[Link]("Month")
[Link]("Sales")
[Link](True)
[Link]()
# Bar plot
191
# Correlation heatmap
[Link]([Link](), annot=True)
[Link]()
[Link]()
report = pd.read_excel("monthly_report.xlsx")
print([Link]())
c = [Link]("sales_report.pdf")
[Link]()
print(pivot)
193
data['date'] = pd.to_datetime(data['date'])
data.set_index('date', inplace=True)
monthly_sales = data['sales'].resample('M').sum()
monthly_sales.plot()
2. S
tock Market Analyzer → yfinance API + moving averages + interactive
dashboard
3. Fetch Bitcoin prices last 30 days → line chart → export PDF
5. Automate Excel + PDF monthly report → total, avg, max sales
19.10 Summary
● Pandas → Data cleaning, transformation
hai, ab tu Data Analysis ke ultimate God ban gaya. Raw data → insights →
B
reports → interactive dashboards = ab terey haath me hai.
196
python --version
197
# Linux/Mac
source fullstack_env/bin/activate
# Windows
fullstack_env\Scripts\activate
fullstack_project/
│
├── backend/
│
├── [Link]
│
├── [Link]
│
└── [Link]
│
├── frontend/
│
├── [Link]
│
├── [Link]
│
└── [Link]
│
├── database/
│
└── [Link]
│
├── reports/
│
└── monthly_report.pdf
│
199
├── data/
│
└── [Link]
│
└── utils/
├── [Link]
└── [Link]
app = Flask(__name__)
@[Link]('/')
def home():
@[Link]('/api/sales', methods=['GET'])
200
def sales_api():
return jsonify(data)
if __name__ == "__main__":
[Link](debug=True)
Example: [Link]
class Product([Link]):
name = [Link](max_length=100)
price = [Link]()
stock = [Link]()
def __str__(self):
return [Link]
[Link]
def dashboard(request):
products = [Link]()
import sqlite3
conn = [Link]('[Link]')
c = [Link]()
[Link]()
[Link]()
engine = create_engine('sqlite:///[Link]')
Base = declarative_base()
class Sale(Base):
__tablename__ = 'sales'
203
id = Column(Integer, primary_key=True)
product = Column(String)
amount = Column(Float)
[Link].create_all(engine)
Session = sessionmaker(bind=engine)
session = Session()
[Link]
<h1>Sales Dashboard</h1>
<div id="chart"></div>
<script>
fetch('/api/sales')
.then(data => {
[Link](data);
204
});
</script>
import requests
esponse =
r
[Link]("[Link]
&appid=YOUR_KEY")
data = [Link]()
print(data['main']['temp'])
def automate_report():
data = pd.read_csv("[Link]")
summary = [Link]('month')['sales'].sum()
summary.to_excel("reports/monthly_report.xlsx")
20.10 Summary
● Backend → Flask/Django
21.1.1 Installation
import tkinter
print([Link])
root = [Link]()
# Create main window
[Link]("400x300")
# Width x Height
[Link](pady=20)
# Add label to window
[Link]()
# Run the GUI
Explanation:
def on_click():
[Link](text="Button Clicked!")
210
[Link](pady=10)
entry = [Link](root)
[Link](pady=10)
def show_entry():
text = [Link]()
entry_button.pack(pady=5)
[Link](pady=20)
frame.pack_propagate(False)
# Prevent auto-resize
inner_label.pack()
var1 = [Link]()
[Link]()
var2 = [Link]()
[Link]()
[Link]()
IntVar/
● StringVar→ Store widget state
212
21.1.7 Menus
menu_bar = [Link](root)
[Link](menu=menu_bar)
file_menu.add_command(label="Open")
file_menu.add_command(label="Save")
file_menu.add_separator()
file_menu.add_command(label="Exit", command=[Link])
menu_bar.add_cascade(label="File", menu=file_menu)
def show_msg():
213
msg_button.pack(pady=10)
[Link]("ID", text="ID")
[Link]("Name", text="Name")
[Link]("Age", text="Age")
214
[Link](pady=20)
● Example:
app = QApplication([])
window = QWidget()
[Link]("PyQt App")
[Link](100,100,300,200)
[Link](50,50)
[Link]()
app.exec_()
215
● Example:
class MyApp(App):
def build(self):
MyApp().run()
Folder Structure
student_management/
├─ [Link]
├─ [Link]
└─ [Link]
218
[Link]
import sqlite3
def create_db():
conn = [Link]("[Link]")
cursor = [Link]()
[Link]("""
name TEXT,
age INTEGER,
grade TEXT
)
""")
[Link]()
[Link]()
conn = [Link]("[Link]")
cursor = [Link]()
[Link]()
219
[Link]()
def fetch_students():
conn = [Link]("[Link]")
cursor = [Link]()
data = [Link]()
[Link]()
return data
def delete_student(student_id):
conn = [Link]("[Link]")
cursor = [Link]()
[Link]()
[Link]()
[Link] (GUI)
create_db()
def add_student_gui():
name = name_entry.get()
age = age_entry.get()
grade = grade_entry.get()
refresh_table()
else:
def refresh_table():
[Link](row)
def delete_student_gui():
selected = [Link]()
if selected:
221
student_id = [Link](selected[0])['values'][0]
delete_student(student_id)
refresh_table()
else:
root = [Link]()
[Link]("600x500")
# Input Fields
[Link](root, text="Name").pack()
name_entry = [Link](root)
name_entry.pack()
[Link](root, text="Age").pack()
age_entry = [Link](root)
age_entry.pack()
[Link](root, text="Grade").pack()
grade_entry = [Link](root)
222
grade_entry.pack()
# Table
[Link]("ID", text="ID")
[Link]("Name", text="Name")
[Link]("Age", text="Age")
[Link]("Grade", text="Grade")
[Link](expand=True, fill="both")
refresh_table()
[Link]()
✅
Concepts used: Variables, functions, loops, OOP optional, file/db handling, GUI
widgets, Treeview tables, message boxes.
Code: weather_app.py
import requests
API_KEY = "YOUR_API_KEY"
def get_weather():
city = city_entry.get()
if not city:
return
rl =
u
f"[Link]
EY}&units=metric"
response = [Link](url)
224
if response.status_code == 200:
data = [Link]()
temp = data["main"]["temp"]
humidity = data["main"]["humidity"]
condition = data["weather"][0]["description"]
esult_label.config(text=f"Temp: {temp}°C\nHumidity:
r
{humidity}%\nCondition: {condition}")
else:
root = [Link]()
[Link]("Weather App")
[Link]("400x300")
city_entry = [Link](root)
city_entry.pack()
result_label.pack(pady=20)
225
[Link]()
✅ Concepts used: API requests, JSON parsing, GUI, error handling, functions.
database_ecommerce.py
import sqlite3
def create_db():
conn = [Link]("[Link]")
cursor = [Link]()
[Link]("""
name TEXT,
price REAL,
quantity INTEGER
)
""")
[Link]()
[Link]()
conn = [Link]("[Link]")
cursor = [Link]()
[Link]()
[Link]()
def fetch_products():
conn = [Link]("[Link]")
cursor = [Link]()
data = [Link]()
[Link]()
227
return data
def delete_product(product_id):
conn = [Link]("[Link]")
cursor = [Link]()
[Link]()
[Link]()
main_ecommerce.py (GUI)
create_db()
def add_product_gui():
name = name_entry.get()
price = price_entry.get()
qty = qty_entry.get()
refresh_table()
else:
def delete_product_gui():
selected = [Link]()
if selected:
product_id = [Link](selected[0])['values'][0]
delete_product(product_id)
refresh_table()
else:
def refresh_table():
[Link](row)
root = [Link]()
229
[Link]("600x500")
# Input Fields
[Link](root, text="Name").pack()
name_entry = [Link](root)
name_entry.pack()
[Link](root, text="Price").pack()
price_entry = [Link](root)
price_entry.pack()
[Link](root, text="Quantity").pack()
qty_entry = [Link](root)
qty_entry.pack()
# Table
[Link]("ID", text="ID")
[Link]("Name", text="Name")
230
[Link]("Price", text="Price")
[Link]("Quantity", text="Quantity")
[Link](expand=True, fill="both")
refresh_table()
[Link]()
✅ Concepts used: Loops, functions, GUI, database, CRUD operations, data validation.
Folder Structure
netflix_clone/
├─ [Link]
├─ [Link]
├─ [Link]
├─ media_player.py
├─ images/
└─ [Link]
[Link]
import sqlite3
def create_db():
conn = [Link]("[Link]")
cursor = [Link]()
[Link]("""
password TEXT
)
232
""")
[Link]("""
user_id INTEGER,
movie_id INTEGER,
movie_name TEXT,
)
""")
[Link]()
[Link]()
conn = [Link]("[Link]")
cursor = [Link]()
[Link]()
[Link]()
conn = [Link]("[Link]")
cursor = [Link]()
result = [Link]()
[Link]()
return result
conn = [Link]("[Link]")
cursor = [Link]()
[Link]()
[Link]()
def fetch_favorites(user_id):
conn = [Link]("[Link]")
cursor = [Link]()
data = [Link]()
[Link]()
234
return data
[Link]
import requests
API_KEY = "YOUR_TMDB_API_KEY"
def search_movie(query):
rl =
u
f"[Link]
uery}"
response = [Link](url)
if response.status_code == 200:
return [Link]()["results"]
return []
def fetch_movie_details(movie_id):
rl =
u
f"[Link]
response = [Link](url)
if response.status_code == 200:
return [Link]()
return {}
235
media_player.py
import webbrowser
def play_trailer(trailer_url):
[Link](trailer_url)
hai, yaha hum simple web browser me trailer open kar rahe hain. Agar
B
chaahe, mai fully embedded Tkinter media player ka code bhi de sakta
hoon.
create_db()
current_user_id = None
236
def signup():
username = username_entry.get()
password = password_entry.get()
try:
add_user(username, password)
except:
else:
def login():
global current_user_id
username = username_entry.get()
password = password_entry.get()
if user:
current_user_id = user[0]
show_main_screen()
else:
237
def search():
query = search_entry.get()
movies = search_movie(query)
movie_tree.delete(row)
for m in movies:
def add_to_favorites():
selected = movie_tree.selection()
if selected:
def show_main_screen():
login_frame.pack_forget()
main_frame.pack(expand=True, fill="both")
root = [Link]()
[Link]("Netflix Clone")
[Link]("800x600")
login_frame = [Link](root)
login_frame.pack(expand=True, fill="both")
[Link](login_frame, text="Username").pack(pady=5)
username_entry = [Link](login_frame)
username_entry.pack(pady=5)
[Link](login_frame, text="Password").pack(pady=5)
password_entry.pack(pady=5)
main_frame = [Link](root)
search_entry = [Link](main_frame)
search_entry.pack(pady=5)
239
movie_tree.heading(col, text=col)
movie_tree.pack(expand=True, fill="both")
[Link]()
THE END
THANK YOU FOR READING
“ Now if you go to the doctor and get
your platelets checked, you will find the
count of the pyhton code and not the
platelet count.”