0% found this document useful (0 votes)
28 views241 pages

Pyhton Textbook Akarsh

This is a book for full stack python developer . It contains around 240 pages and 21 chapter containing all the types topic
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
28 views241 pages

Pyhton Textbook Akarsh

This is a book for full stack python developer . It contains around 240 pages and 21 chapter containing all the types topic
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

P‭ ython DNA: Code in Your‬

‭Blood‬
‭─‬
‭1‬

‭📖 Chapter 1: Introduction to Python‬

‭1.1 What is Programming?‬


‭Before learning Python, we must first understand‬‭what‬‭programming actually means‬‭.‬

‭●‬ ‭A‬‭computer‬‭is a powerful machine, but it cannot think‬‭like humans.‬

‭●‬ ‭It only understands‬‭binary language (0s and 1s)‬‭.‬

‭●‬ ‭Writing in binary is nearly impossible for humans.‬

‭ his is why‬‭programming languages‬‭were invented —‬‭they act as a bridge between‬


T
‭human thinking‬‭and‬‭computer understanding‬‭.‬

💡
‭ ‬‭Analogy:‬
‭Think of a robot that you want to cook noodles. You cannot just say,‬‭“Make Maggi!”‬‭. You‬
‭must give step-by-step instructions:‬

‭1.‬ ‭Take water.‬

‭2.‬ ‭Boil the water.‬

‭3.‬ ‭Add noodles.‬

‭4.‬ ‭Add spices.‬

‭5.‬ ‭Cook for 2 minutes.‬

‭ his process of breaking down tasks into‬‭small, clear‬‭steps‬‭is called‬‭algorithmic thinking‬‭.‬


T
‭Programming is the art of expressing these steps in a language that a computer can‬
‭execute.‬
‭2‬

‭Notes:‬

‭●‬ ‭Computers are‬‭fast but dumb‬‭.‬

‭●‬ ‭Humans are‬‭smart but slow‬‭.‬

‭●‬ ‭Programming is the bridge.‬

‭Exercise 1.1‬

‭1.‬ ‭Write down step-by-step instructions for brushing your teeth.‬

‭2.‬ ‭Do the same for making tea.‬

‭3.‬ ‭Do you notice how these instructions resemble programming steps?‬

‭1.2 What is Python?‬


‭Python is a‬‭high-level, interpreted, general-purpose‬‭programming language‬‭.‬

‭●‬ ‭High-level‬‭→ closer to human language than machine‬‭language.‬


‭3‬

‭●‬ ‭Interpreted‬‭→ code runs line by line (no need to compile).‬

‭●‬ G
‭ eneral-purpose‬‭→ you can use it in almost every domain‬‭(web, AI, data science,‬
‭automation, etc.).‬

‭💡‬‭Analogy:‬

‭●‬ ‭C language is like‬‭Sanskrit‬‭: powerful, but complex.‬

‭●‬ ‭Java is like‬‭Latin‬‭: widely used, but structured and‬‭formal.‬

‭●‬ ‭Python is like‬‭English‬‭: easy, flexible, and spoken‬‭everywhere.‬

‭Fun Fact:‬

‭ ython is‬‭not named after the snake!‬‭🐍 It comes from‬‭a British comedy show‬‭“Monty‬
P
‭Python’s Flying Circus”‬‭.‬

‭Exercise 1.2‬

‭1.‬ ‭Write in your own words: what does “high-level” mean?‬

‭2.‬ ‭Compare Python with at least one other programming language (C, Java, etc.).‬
‭4‬

‭1.3 Why is Python So Popular?‬


‭Python is one of the‬‭most popular programming languages‬‭today.‬

‭Key Reasons‬

‭1.‬ ‭Readable & simple syntax‬‭(looks like English).‬

‭2.‬ ‭Large community‬‭of developers worldwide.‬

‭3.‬ ‭Libraries for everything‬‭(AI, ML, web, data, graphics).‬

‭4.‬ ‭Cross-platform‬‭(runs on Windows, macOS, Linux).‬

‭5.‬ ‭Trusted by big companies‬‭(Google, Netflix, NASA, Instagram,‬‭Spotify).‬

💡
‭ ‬‭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‬

‭1.‬ ‭Write the names of 5 famous companies that use Python.‬

‭2.‬ ‭Why do you think scientists prefer Python over C++?‬

‭1.4 A Short History of Python‬


‭●‬ 1
‭ 980s‬‭→ Guido van Rossum (Netherlands) worked on a‬‭project called “ABC‬
‭language”. It was simple but not widely adopted.‬

‭●‬ ‭1989‬‭→ Guido started designing Python during Christmas‬‭holidays.‬

‭●‬ ‭1991‬‭→ First release of Python (version 0.9).‬

‭●‬ ‭2000‬‭→ Python 2.0 released with major features (Unicode,‬‭garbage collection).‬

‭●‬ ‭2008‬‭→ Python 3.0 released. Cleaner, modern, but not‬‭backward compatible.‬

‭●‬ ‭2020‬‭→ Python 2 officially retired.‬

‭●‬ ‭Today‬‭→ Python 3.x dominates the world of programming.‬


‭6‬

‭Fun Fact:‬

‭ uido van Rossum was humorously called the‬‭“Benevolent‬‭Dictator For Life (BDFL)”‬
G
‭because of his central role in guiding Python’s development.‬

‭Exercise 1.4‬

‭1.‬ ‭Who created Python and when?‬

‭2.‬ ‭What was the biggest reason for creating Python 3?‬

‭1.5 Features of Python‬


‭●‬ ‭Readable syntax‬‭→ like plain English.‬

‭●‬ ‭Object-oriented‬‭→ everything is treated as an object.‬

‭●‬ ‭Dynamic typing‬‭→ no need to declare variable type.‬

‭●‬ ‭Rich libraries‬‭→ pre-built tools for almost every‬‭task.‬

‭●‬ ‭Embeddable‬‭→ can be combined with C/C++.‬


‭7‬

‭●‬ ‭Interpreted‬‭→ runs line by line.‬

‭💡‬‭Diagram:‬

‭our Code (.py) → Interpreter → Bytecode → Python Virtual Machine →‬


Y
Output‬

‭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‬

‭1.‬ ‭List 3 advantages of Python.‬

‭2.‬ ‭List 2 disadvantages.‬


‭8‬

‭1.6 Installing Python‬

‭Steps:‬

‭1.‬ ‭Download from‬‭[Link]‬‭.‬

‭2.‬ ‭Run installer → check “Add to PATH”.‬

‭Verify installation:‬

python --version‬

‭3.‬

‭Popular IDEs for Python‬

‭●‬ ‭IDLE‬‭(comes with Python).‬

‭●‬ ‭VS Code‬‭(lightweight, highly recommended).‬

‭●‬ ‭PyCharm‬‭(professional).‬

‭Mini Project 1.6‬


‭9‬

‭Write a Python program that prints:‬

Hello! My name is <your name>.‬


I am learning Python.‬

‭1.7 Your First Python Program‬

‭Example:‬
print("Hello, World!")‬

‭10‬

print()‬‭→ a function in Python.‬


‭●‬ ‭

"Hello, World!"‬‭→ string value to display.‬


‭●‬ ‭

💡
‭ ‬‭Why “Hello, World!”?‬
‭It’s like saying‬‭“Mic check, 1…2…3”‬‭before a concert.‬

‭Predict the Output Exercise:‬

‭What will this code print?‬

print("Python " * 3)‬


‭1.8 Where Can Python Be Used?‬


‭●‬ ‭Web Development‬‭→ Django, Flask.‬

‭●‬ ‭Data Science‬‭→ Pandas, NumPy.‬


‭11‬

‭●‬ ‭Artificial Intelligence & Machine Learning‬‭→ TensorFlow, PyTorch.‬

‭●‬ ‭Automation (Scripting)‬‭→ Repetitive tasks.‬

‭●‬ ‭Cybersecurity‬‭→ Pentesting tools.‬

‭●‬ ‭Game Development‬‭→ Pygame.‬

‭●‬ ‭Desktop Applications‬‭→ Tkinter, PyQt.‬

‭Mini Project 1.8‬

‭Create a script that asks for your name and then prints:‬

Welcome, <name>! You are now a Python learner.‬


‭✅ Summary of Chapter 1‬
‭12‬

‭●‬ ‭Programming = giving instructions to a computer.‬

‭●‬ ‭Python = high-level, interpreted, general-purpose language.‬

‭●‬ ‭Named after Monty Python (not the snake).‬

‭●‬ ‭Extremely popular due to simplicity, libraries, and community.‬

‭●‬ ‭Used in almost every modern tech domain.‬


‭13‬

‭📖 Chapter 2: Python Basics – Variables, Data Types, and Operators‬

‭2.1 Variables – The Named Containers‬


‭Imagine your brain as a giant cupboard 🗄️. Inside it, you have boxes with labels:‬

‭●‬ ‭“Math Formulas”‬

‭●‬ ‭“Birthday Memories”‬

‭●‬ ‭“Phone Numbers”‬

‭ henever you need something, you don’t search the whole cupboard; you just look at the‬
W
‭label.‬

‭This is exactly what a‬‭variable‬‭is in Python.‬

‭●‬ ‭A‬‭name‬‭that points to a value stored in memory.‬

‭●‬ ‭You don’t need to know the‬‭exact address‬‭in memory‬‭— you just use the label.‬

‭Example:‬

age = 21‬

name = "Akarsh"‬

pi = 3.14159‬

age‬‭→ variable holding an integer.‬


‭●‬ ‭

name‬‭→ variable holding a string.‬


‭●‬ ‭
‭14‬

pi‬‭→ variable holding a float.‬


‭●‬ ‭

‭Notes:‬

‭●‬ ‭Variables are‬‭case-sensitive‬‭→‬‭


Age‬‭≠‬‭ ‭.‬
age‬

‭●‬ ‭They are created when you assign them.‬

‭Pitfall:‬

‭Avoid using reserved keywords as variable names (‬‭


if‬‭,‬‭ ‭,‬‭
for‬ ‭, etc.).‬
class‬

‭Exercise 2.1‬

‭1.‬ ‭Create variables for your‬‭name‬‭,‬‭age‬‭, and‬‭favorite‬‭subject‬‭.‬

‭Print them in a sentence:‬

My name is Rahul. I am 19 years old. My favorite‬‭


‭ subject is Physics.‬

‭2.‬

‭2.2 Rules for Naming Variables‬


‭Python enforces rules, like a school dress code.‬

‭✅ Allowed:‬

‭●‬ ‭Letters (a–z, A–Z)‬

‭●‬ ‭Digits (0–9)‬


‭15‬

‭●‬ ‭Underscore‬‭
_‬

‭❌ Not Allowed:‬

‭●‬ ‭Cannot start with a digit.‬

‭●‬ ‭Cannot contain spaces.‬

‭●‬ ‭Cannot use special characters (@, #, $, %).‬

‭Examples:‬

valid_name = "Rahul"‬

_name123 = "Python"‬

rollNumber = 45‬

‭❌ Invalid:‬

123name = "wrong"‬

my-name = "wrong"‬

class = "reserved keyword"‬


‭Exercise 2.2‬

‭Mark each variable as‬‭valid or invalid‬‭:‬

‭1.‬ ‭
2cool‬

‭2.‬ ‭
cool2‬

‭3.‬ ‭
_hidden‬
‭16‬

‭4.‬ ‭
break‬

‭5.‬ ‭
my name‬

‭2.3 Data Types in Python‬


‭Every value in Python has a‬‭type‬‭.‬

‭Core Data Types:‬

‭int‬‭→ Whole numbers‬

age = 25‬

temperature = -5‬

‭1.‬

‭float‬‭→ Decimal numbers‬

pi = 3.14‬

height = 1.82‬

‭2.‬

‭str‬‭→ Strings (text)‬

name = "Python"‬

sentence = "I love coding!"‬


‭3.‬

‭bool‬‭→ Boolean values (True/False)‬

is_student = True‬

is_coder = False‬

‭17‬

‭4.‬

‭Sneak Peek: Advanced Types‬

‭●‬ ‭list‬‭→ collection of values‬‭


[1, 2, 3]‬

‭●‬ ‭tuple‬‭→ fixed collection‬‭


(1, 2, 3)‬

‭●‬ ‭dict‬‭→ key-value pairs‬‭


{"name": "Rahul", "age": 20}‬

‭●‬ ‭set‬‭→ unique items‬‭


{1, 2, 3}‬

‭Fun Fact:‬

‭Python automatically figures out the type. Unlike Java or C, you don’t have to declare it.‬

‭Exercise 2.3‬

‭1.‬ ‭Create variables for:‬

‭○‬ ‭Your‬‭age‬‭(int)‬

‭○‬ ‭Your‬‭height‬‭(float)‬

‭○‬ ‭Whether you like Python (bool)‬

‭2.‬ ‭Print all of them in one sentence.‬

‭2.4 Type Conversion (Casting)‬


‭Sometimes you must convert one type into another.‬
‭18‬

‭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:‬

‭Not everything can be converted:‬

int("hello")
‭ # ❌ Error‬

‭Exercise 2.4‬

‭1.‬ ‭Convert‬‭
"3.14"‬‭(string) into a float.‬

‭2.‬ ‭Convert‬‭
1‬‭into a boolean.‬

‭3.‬ ‭Convert‬‭
True‬‭into an integer.‬
‭19‬

‭2.5 Operators in Python‬


‭Operators are like tools 🛠️ to work on data.‬

‭Types of Operators‬

‭1.‬ ‭Arithmetic Operators‬

+‬‭addition‬
‭○‬ ‭

-‬‭subtraction‬
‭○‬ ‭

*‬‭multiplication‬
‭○‬ ‭

/‬‭division‬
‭○‬ ‭

%‬‭modulus (remainder)‬
‭○‬ ‭

**‬‭exponentiation‬
‭○‬ ‭

//‬‭floor division‬
‭○‬ ‭

print(5 + 2)
‭ # 7‬

print(5 % 2)
‭ # 1‬

print(2 ** 3)
‭ # 8‬

‭2.‬

‭2.‬ ‭Comparison Operators‬

==‬‭equal‬
‭○‬ ‭

!=‬‭not equal‬
‭○‬ ‭
‭20‬

>‬‭greater than‬
‭○‬ ‭

<‬‭less than‬
‭○‬ ‭

>=‬‭greater or equal‬
‭○‬ ‭

<=‬‭less or equal‬
‭○‬ ‭

print(5 > 2)
‭ # True‬

print(5 == 2)
‭ # False‬

‭3.‬

‭3.‬ ‭Logical Operators‬

and‬‭→ True if both are true‬


‭○‬ ‭

or‬‭→ True if at least one is true‬


‭○‬ ‭

not‬‭→ negates value‬


‭○‬ ‭

print(True and False)


‭ # False‬

print(True or False)
‭ # True‬

print(not True)
‭ # False‬

‭4.‬

‭4.‬ ‭Assignment Operators‬

=‬‭assignment‬
‭○‬ ‭

‭○‬ ‭ ‭,‬‭
+=‬ ‭,‬‭
-=‬ ‭,‬‭
*=‬ /=‬‭etc. (update shorthand)‬
‭21‬

x = 5‬

x += 2
‭ # x = x + 2‬

print(x) # 7‬

‭5.‬

‭5.‬ ‭Membership Operators‬

‭○‬ ‭ ‭,‬‭
in‬ not in‬

fruits = ["apple", "banana"]‬


print("apple" in fruits)
‭ # True‬

print("mango" not in fruits) # True‬


‭6.‬

‭6.‬ ‭Identity Operators‬

‭○‬ ‭ ‭,‬‭
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‬

‭1.‬ ‭Write a program to check if your age is greater than 18.‬

‭2.‬ ‭Create two numbers and perform all arithmetic operations.‬

‭3.‬ ‭Create a list of your favorite foods and check if‬‭


"pizza"‬‭is in it.‬

‭✅ Chapter 2 Summary‬
‭●‬ ‭Variables are‬‭named containers‬‭for data.‬

‭●‬ N
‭ aming rules: can use letters, numbers, underscore (but no spaces, special symbols,‬
‭or keywords).‬

‭●‬ ‭Python has‬‭core data types‬‭: int, float, str, bool.‬

‭●‬ ‭You can‬‭convert types‬‭using functions like‬‭ ‭,‬‭


int()‬ ‭.‬
str()‬

‭●‬ ‭Python provides many‬‭operators‬‭for calculations and logic.‬


‭23‬

‭📖 Chapter 3: Python Control Flow – Conditional Statements and Loops‬


‭(Expanded)‬

‭3.1 Conditional Statements – “If, Elif, Else”‬

‭Real-Life Analogy‬

‭Imagine you are playing a game. You have‬‭three choices‬‭:‬

‭1.‬ ‭Jump‬

‭2.‬ ‭Run‬

‭3.‬ ‭Hide‬

‭In Python, we can write these decisions using‬‭if,‬‭elif, else‬‭statements:‬

action = input("Choose your action (jump/run/hide): ")‬


if action == "jump":‬

print("You jumped over the obstacle!")‬


elif action == "run":‬


print("You ran fast!")‬


else:‬

print("You are hiding now!")‬


‭●‬ ‭If the user types‬‭ ‭, the first block executes‬


"jump"‬
‭24‬

‭●‬ ‭If‬‭ ‭, the second block executes‬


"run"‬

‭●‬ ‭Any other input → the else block executes‬

‭ ip: Python uses‬‭indentation‬‭to define blocks. Improper‬‭indentation will cause‬


T
‭errors.‬

‭Comparison Operators‬

‭Conditional statements use‬‭comparison operators‬‭:‬

‭Operator‬ ‭Meaning‬ ‭Example‬

==‬
‭ ‭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‬

‭To check multiple conditions:‬


‭25‬

‭Operator‬ ‭Meaning‬ ‭Example‬

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‬

‭Exercise 3.1 – Conditional Statements‬

‭1.‬ ‭Ask the user for a number. Print whether it is‬‭positive,‬‭negative, or zero‬‭.‬

‭2.‬ ‭Create a temperature checker (Celsius → Hot, Pleasant, Cold).‬

‭3.‬ ‭Take marks → assign grades: A, B, C, Fail.‬

‭4.‬ ‭Ask age → if >=18 → “Can vote”, else → “Cannot vote”.‬

‭5.‬ ‭Ask for username → if correct → print welcome, else → “Try again”.‬

‭3.2 Nested If Statements‬


‭Nested if statements are used when‬‭a decision depends‬‭on another decision‬‭.‬

‭Example 3.2‬

marks = 85‬

attendance = 90‬

‭26‬

if marks >= 75:‬


if attendance >= 80:‬


print("You passed with distinction!")‬


else:‬

print("You passed but attendance is low.")‬


else:‬

print("You did not pass.")‬


‭●‬ ‭Marks ≥75 and attendance ≥80 → distinction‬

‭●‬ ‭Marks ≥75 and attendance <80 → passed but low attendance‬

‭●‬ ‭Marks <75 → fail‬

‭Exercise 3.2 – Nested If‬

‭1.‬ ‭Ask the user for age and temperature:‬

‭○‬ ‭If age > 18 → Check temperature: >30 Hot, else Pleasant‬

‭2.‬ ‭Bank system: Ask for‬‭PIN‬‭and‬‭balance‬‭:‬

‭○‬ ‭Correct PIN → check balance → if balance >0 print “Active”, else “Overdrawn”‬

‭○‬ ‭Incorrect PIN → “Access Denied”‬

‭3.3 Loops – Repeating Tasks‬


‭27‬

‭Loops help us‬‭repeat code automatically‬‭.‬

‭3.3.1 For Loop‬

‭Iterating over a String‬

word = "Python"‬

for letter in word:‬


print(letter)‬

‭Output:‬

P‬

y‬

t‬

h‬

o‬

n‬

‭Using Range in For Loop‬

for i in range(2, 11, 2):


‭ # start, stop, step‬

print(i)‬

‭Output: 2, 4, 6, 8, 10‬

‭Nested For Loop‬


‭28‬

for i in range(1, 4):‬


for j in range(1, 4):‬


print(f"i={i}, j={j}")‬

‭Output:‬

i=1, j=1‬

i=1, j=2‬

...‬

i=3, j=3‬

‭Exercise 3.3 – For Loop‬

‭1.‬ ‭Print multiplication table of 5.‬

‭2.‬ ‭Print pattern:‬

*‬

**‬

***‬

****‬

‭3.‬ ‭Print all odd numbers from 1–50.‬

‭4.‬ ‭Iterate a list of cities → print‬‭ ‭.‬


"Welcome to <city>"‬
‭29‬

‭5.‬ ‭Nested loop: Print coordinates (x, y) for x=1-3, y=1-3.‬

‭3.3.2 While Loop‬

‭Basic While Loop‬

i = 1‬

while i <= 5:‬


print(i)‬

i += 1‬

‭Infinite While Loop with Break‬

while True:‬

user_input = input("Type 'exit' to stop: ")‬


if user_input == "exit":‬

break‬

‭Exercise 3.4 – While Loop‬

‭1.‬ ‭Print numbers 1–10 using while.‬

‭2.‬ ‭Sum numbers until user enters 0.‬

‭3.‬ ‭Ask for password until correct.‬

‭4.‬ ‭Print factorial of a number.‬


‭30‬

‭3.4 Loop Control Statements‬


‭●‬ ‭Break‬‭– stop the loop‬

‭●‬ ‭Continue‬‭– skip current iteration‬

‭●‬ ‭Pass‬‭– placeholder‬

# Break example‬

for i in range(1, 20):‬


if i % 7 == 0:‬

break‬

# Continue example‬

for i in range(1, 11):‬


if i % 2 == 0:‬

continue‬

print(i)‬

# Pass example‬

for i in range(1, 6):‬


if i == 3:‬

pass‬

print(i)‬

‭31‬

‭Exercise 3.5 – Loop Controls‬

‭1.‬ ‭Print numbers 1–50, skip multiples of 3, stop if >40.‬

‭2.‬ ‭Take numbers → skip negatives, stop on 999.‬

‭3.‬ ‭Iterate list → skip “apple”, pass “banana”, print rest.‬

‭3.5 Mini Project – Guess the Number Game‬


import random‬

number = [Link](1, 50)‬


guess = 0‬

attempts = 0‬

while guess != number:‬


guess = int(input("Guess the number (1-50): "))‬


attempts += 1‬

if guess < number:‬


print("Too low!")‬

elif guess > number:‬


print("Too high!")‬

else:‬

‭32‬

print(f"Congratulations! You guessed in {attempts} attempts.")‬


‭✅‬‭Chapter 3 Summary‬

‭●‬ ‭Conditional Statements → if, elif, else‬

‭●‬ ‭Nested If → decision inside a decision‬

‭●‬ ‭Loops → for, while‬

‭●‬ ‭Loop Controls → break, continue, pass‬

‭●‬ ‭Mini Project → Guess the Number Game‬


‭33‬

‭📖 Chapter 4: Python Functions – Building Blocks of Code‬

‭4.1 What is a Function?‬


‭Think of a function as a‬‭machine‬‭:‬

‭●‬ ‭You give it‬‭inputs‬‭→ it performs‬‭work‬‭→ gives‬‭output‬‭.‬

‭●‬ ‭Functions‬‭help avoid repeating code‬‭and make programs‬‭organized.‬

‭Analogy:‬

I‭magine you have a‬‭juice machine‬‭. You put fruits in‬‭→ it gives juice. You don’t need to‬
‭manually squeeze every time.‬

‭4.2 Creating a Function‬

def greet():‬

print("Hello, brother!")‬

def‬‭→ keyword to define a function‬


‭●‬ ‭

greet‬‭→ function name‬


‭●‬ ‭

()‬‭→ parentheses, can hold inputs (parameters)‬


‭●‬ ‭

:‬‭→ start of function block‬


‭●‬ ‭

greet()
‭ # Calling the function‬
‭34‬

‭Output:‬

Hello, brother!‬

‭4.3 Function Parameters and Arguments‬

‭Functions can take‬‭inputs‬‭.‬

def greet(name):‬

print(f"Hello, {name}!")‬

greet("Akarsh")‬

greet("Python Legend")‬

‭Output:‬

Hello, Akarsh!‬

Hello, Python Legend!‬


name‬‭→‬‭parameter‬
‭●‬ ‭

"Akarsh"‬‭→‬‭argument‬
‭●‬ ‭

‭4.4 Return Statement‬

return‬‭gives a value back from the function‬


‭●‬ ‭
‭35‬

def add(a, b):‬


return a + b‬

result = add(5, 7)‬


print(result)‬

‭Output:‬

12‬

‭4.5 Types of Functions‬

‭Type‬ ‭Example‬

‭No parameter, no return‬ ‭ef greet():‬


d
print("Hi")‬

‭With parameter, no return‬ ‭ef greet(name):‬


d
print(name)‬

‭No parameter, with return‬ ‭ef get_number():‬


d
return 42‬

‭With parameter and return‬ ‭ef add(a,b):‬


d
return a+b‬

‭Exercise 4.1 – Functions Basics‬

‭1.‬ ‭Write a function that prints your name.‬


‭36‬

‭2.‬ ‭Write a function that adds two numbers and prints the result.‬

‭3.‬ ‭Write a function that takes temperature in Celsius and returns Fahrenheit.‬

‭4.‬ ‭Write a function that checks if a number is even or odd.‬

‭5.‬ ‭Create a function that says “Good Morning” based on the time of day.‬

‭4.6 Default and Keyword Arguments‬

‭Default Values‬

def greet(name="Brother"):‬

print(f"Hello, {name}!")‬

greet()
‭ # Hello, Brother!‬

greet("Akarsh")
‭ # Hello, Akarsh!‬

‭Keyword Arguments‬

def describe(name, age):‬


print(f"{name} is {age} years old.")‬


describe(age=20, name="Akarsh")‬

‭Output:‬

Akarsh is 20 years old.‬



‭37‬

‭Tip:‬‭Keyword arguments‬‭help when you want to‬‭pass‬‭in any order‬‭.‬

‭4.7 Variable Scope – Local vs Global‬

‭●‬ ‭Local variable‬‭→ exists inside function‬

‭●‬ ‭Global variable‬‭→ exists outside function‬

x = 10
‭ # global‬

def show():‬

y = 5
‭ # local‬

print(x, y)‬

show()‬

print(x)‬

# print(y) → Error, y is local‬


‭4.8 Lambda Functions (Anonymous Functions)‬

‭●‬ ‭Small, one-line functions‬

‭●‬ ‭Useful for‬‭quick calculations‬

square = lambda x: x ** 2‬

‭38‬

print(square(5))
‭ # 25‬

add = lambda a, b: a + b‬

print(add(10, 15))
‭ # 25‬

‭4.9 Recursion – Function Calling Itself‬

‭●‬ ‭A function can‬‭call itself‬

‭●‬ ‭Useful for problems like‬‭factorial, Fibonacci‬

def factorial(n):‬

if n == 0:‬

return 1‬

else:‬

return n * factorial(n-1)‬

print(factorial(5))
‭ # 120‬

‭Exercise 4.2 – Advanced Functions‬

‭1.‬ ‭Write a function to calculate factorial using recursion.‬

‭2.‬ ‭Write a function to find the nth Fibonacci number.‬


‭39‬

‭3.‬ ‭Write a function to check if a number is prime.‬

‭4.‬ ‭Write a lambda function to calculate the cube of a number.‬

‭5.‬ ‭Write a function that returns the maximum of 3 numbers.‬

‭4.10 Mini Project – Calculator Using Functions‬

def add(a, b):‬


return a + b‬

def subtract(a, b):‬


return a - b‬

def multiply(a, b):‬


return a * b‬

def divide(a, b):‬


if b != 0:‬

return a / b‬

else:‬

return "Cannot divide by zero!"‬


while True:‬

print("Options: add, subtract, multiply, divide, exit")‬



‭40‬

choice = input("Choose operation: ")‬


if choice == "exit":‬

break‬

x = float(input("Enter first number: "))‬


y = float(input("Enter second number: "))‬


if choice == "add":‬

print(add(x, y))‬

elif choice == "subtract":‬


print(subtract(x, y))‬

elif choice == "multiply":‬


print(multiply(x, y))‬

elif choice == "divide":‬


print(divide(x, y))‬

else:‬

print("Invalid choice!")‬

‭✅‬‭Chapter 4 Summary‬

‭●‬ ‭Functions → reusable blocks of code‬

‭●‬ ‭Parameters & Arguments → input values‬


‭41‬

‭●‬ ‭Return → output value‬

‭●‬ ‭Default & Keyword Arguments → flexible input‬

‭●‬ ‭Scope → Local vs Global‬

‭●‬ ‭Lambda → one-line anonymous functions‬

‭●‬ ‭Recursion → functions calling themselves‬

‭●‬ ‭Mini Project → Basic Calculator‬


‭42‬

‭📖 Chapter 5: Python Data Structures – Lists, Tuples, Sets, and‬


‭Dictionaries‬

‭5.1 What are Data Structures?‬


‭●‬ ‭Data Structures are‬‭containers‬‭to store and organize‬‭data.‬

‭●‬ ‭They make it easier to‬‭access, modify, and manipulate‬‭data‬‭.‬

‭●‬ ‭Python has four main built-in data structures:‬

‭1.‬ ‭List‬‭→ ordered, mutable‬

‭2.‬ ‭Tuple‬‭→ ordered, immutable‬

‭3.‬ ‭Set‬‭→ unordered, unique elements‬

‭4.‬ ‭Dictionary‬‭→ key-value pairs‬

‭5.2 Lists – The Flexible Container‬


‭●‬ ‭Lists store‬‭multiple items‬‭in a single variable‬

‭●‬ ‭Syntax:‬

my_list = [10, 20, 30, "Python", True]‬


print(my_list)‬

‭Output:‬
‭43‬

[10, 20, 30, 'Python', True]‬


‭List Operations‬

‭Operation‬ ‭Example‬ ‭Output‬

‭Access element‬ my_list[1]‬


‭ ‭20‬

‭Negative indexing‬ my_list[-1]‬


‭ ‭True‬

‭Slicing‬ my_list[1:4]‬
‭ ‭[20,30,'Python']‬

‭Add element‬ ‭y_list.appen‬ ‭adds 50 at end‬


m
d(50)‬

‭Insert element‬ ‭y_list.inser‬ ‭inserts 25 at index 2‬


m
t(2, 25)‬

‭Remove element‬ ‭y_list.remov‬ ‭removes first 30‬


m
e(30)‬

‭Length‬ len(my_list)‬
‭ ‭6‬

‭Sort‬ ‭y_list.sort(‬ ‭sorts numeric list‬


m
)‬

‭Exercise 5.1 – Lists‬

‭1.‬ ‭Create a list of 10 numbers and print the largest.‬

‭2.‬ ‭Create a list of your favorite fruits and add 2 more.‬

‭3.‬ ‭Remove the second and third elements from a list.‬


‭44‬

‭4.‬ ‭Reverse a list using slicing.‬

‭5.‬ ‭Sort a list of random numbers.‬

‭5.3 Tuples – Immutable Lists‬


‭●‬ ‭Tuples are like lists but‬‭cannot be changed‬‭after‬‭creation.‬

‭●‬ ‭Syntax:‬

my_tuple = (1, 2, 3, "Python")‬


print(my_tuple)‬

‭●‬ ‭Why use tuples?‬‭Faster than lists and ensures data‬‭integrity.‬

‭Tuple Operations‬

‭Operation‬ ‭Example‬ ‭Output‬

‭Access element‬ my_tuple[1]‬


‭ ‭2‬

‭Length‬ ‭en(my_tuple‬ ‭4‬


l
)‬

‭Count‬ ‭y_tuple.cou‬ ‭1‬


m
nt(2)‬

‭Index‬ ‭y_tuple.ind‬ ‭2‬


m
ex(3)‬

‭45‬

‭Exercise 5.2 – Tuples‬

‭1.‬ ‭Create a tuple with 5 numbers and print the sum.‬

‭2.‬ ‭Check if a value exists in a tuple.‬

‭3.‬ ‭Find the index of a specific element.‬

‭4.‬ ‭Count how many times a value appears in a tuple.‬

‭5.4 Sets – Unique Elements Only‬


‭●‬ ‭Sets‬‭store unique items‬‭and are‬‭unordered‬‭.‬

‭●‬ ‭Syntax:‬

my_set = {10, 20, 30, 20, 10}‬


print(my_set)‬

‭Output:‬

{10, 20, 30}‬


‭Set Operations‬

‭Operation‬ ‭Example‬ ‭Output‬

‭Add element‬ ‭y_set.add(4‬ ‭{10,20,30,40}‬


m
0)‬

‭46‬

‭Remove element‬ ‭y_set.remov‬ ‭{10,30,40}‬


m
e(20)‬

‭Union‬ ‭̀set1‬ ‭set2`‬

‭Intersection‬ set1 & set2‬


‭ ‭common elements‬

‭Difference‬ set1 - set2‬


‭ ‭elements in set1 not in set2‬

‭Exercise 5.3 – Sets‬

‭1.‬ ‭Create two sets and find union and intersection.‬

‭2.‬ ‭Remove duplicate elements from a list using a set.‬

‭3.‬ ‭Add a new element to a set.‬

‭4.‬ ‭Check if a value exists in a set.‬

‭5.‬ ‭Find elements in one set but not in another.‬

‭5.5 Dictionaries – Key-Value Pairs‬


‭●‬ ‭Dictionaries store data as‬‭key-value pairs‬‭.‬

‭●‬ ‭Syntax:‬

my_dict = {"name": "Akarsh", "age": 20, "language": "Python"}‬


print(my_dict)‬

‭47‬

‭Output:‬

{'name': 'Akarsh', 'age': 20, 'language': 'Python'}‬


‭Dictionary Operations‬

‭Operation‬ ‭Example‬ ‭Output‬

‭Access value‬ my_dict["name"]‬


‭ ‭'Akarsh'‬

‭Add/Update value‬ ‭y_dict["age"]=2‬ ‭updates age‬


m
1‬

‭Remove key‬ ‭y_dict.pop("lan‬ ‭removes key‬


m
guage")‬

‭Keys‬ my_dict.keys()‬
‭ ‭dict_keys([...])‬

‭Values‬ my_dict.values()‬ ‭dict_values([...])‬


‭Items‬ my_dict.items()‬
‭ ‭dict_items([...])‬

‭Exercise 5.4 – Dictionaries‬

‭1.‬ ‭Create a dictionary with your favorite movies and their release years.‬

‭2.‬ ‭Update the year of a movie.‬

‭3.‬ ‭Remove one movie from the dictionary.‬

‭4.‬ ‭Print all keys and values.‬

‭5.‬ ‭Check if a movie exists in the dictionary.‬


‭48‬

‭5.6 Nested Data Structures‬


‭●‬ ‭Python allows‬‭lists inside dictionaries‬‭,‬‭dictionaries‬‭inside lists‬‭, etc.‬

data = {‬

"students": [‬

{"name": "Akarsh", "age": 20},‬


{"name": "Python Legend", "age": 21}‬


]‬

}‬

print(data["students"][1]["name"])
‭ # Python Legend‬

‭Mini Project 5 – Student Management System‬

‭●‬ ‭Create a dictionary to store‬‭student info (name, age,‬‭marks)‬‭.‬

‭●‬ ‭Features:‬

‭1.‬ ‭Add a new student‬

‭2.‬ ‭Remove a student‬

‭3.‬ ‭Update marks‬

‭4.‬ ‭Print all student info‬

students = {}‬

‭49‬

def add_student(name, age, marks):‬


students[name] = {"age": age, "marks": marks}‬


def remove_student(name):‬

[Link](name, None)‬

def update_marks(name, marks):‬


if name in students:‬

students[name]["marks"] = marks‬

def show_students():‬

for name, info in [Link]():‬


print(name, info)‬

# Example Usage‬

add_student("Akarsh", 20, 95)‬


add_student("Python Legend", 21, 98)‬


update_marks("Akarsh", 97)‬

show_students()‬

remove_student("Python Legend")‬

show_students()‬

‭50‬

‭✅‬‭Chapter 5 Summary‬

‭●‬ ‭Lists → ordered, mutable, versatile‬

‭●‬ ‭Tuples → ordered, immutable‬

‭●‬ ‭Sets → unordered, unique‬

‭●‬ ‭Dictionaries → key-value pairs‬

‭●‬ ‭Nested structures → combine lists, tuples, dicts‬


‭51‬

‭📖 Chapter 6: Python Strings – Mastering Text Data‬

‭6.1 What is a String?‬


‭●‬ ‭String‬‭is a sequence of‬‭characters‬‭, like letters,‬‭numbers, symbols.‬

‭●‬ S
‭ trings are‬‭immutable‬‭, which means you cannot change‬‭individual characters‬
‭directly.‬

‭●‬ ‭Syntax:‬

text = "Hello, Python!"‬


print(text)‬

‭Output:‬
‭52‬

Hello, Python!‬

‭●‬ S
‭ trings can be in‬‭single quotes‬‭ ‭, double quotes‬‭
' '‬ ‭, or triple quotes‬‭
" "‬ ''' '''‬
‭/‬‭
""" """‬‭for multi-line strings.‬

‭6.2 Accessing Characters and Slicing‬


‭●‬ ‭Access characters using‬‭index‬‭:‬

text = "Python"‬

print(text[0])
‭ # P‬
‭53‬

print(text[-1]) # n (last character)‬


‭●‬ ‭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‬

‭6.3 String Operations‬


‭Operation‬ ‭Example‬ ‭Output‬

‭Concatenation‬ ‭Hello " +‬


" ‭Hello World‬
"World"‬

‭Repetition‬ "Hi"*3‬
‭ ‭HiHiHi‬

‭Length‬ ‭en("Python"‬ ‭6‬


l
)‬

‭55‬

‭Membership‬ ‭P' in‬


' ‭True‬
"Python"‬

‭Escape Characters‬ ‭Hello\nWorl‬ ‭Hello (newline) World‬


"
d"‬

‭Common Escape Characters‬

‭Character‬ ‭Meaning‬

\n‬
‭ ‭New line‬

\t‬
‭ ‭Tab‬
‭56‬

\\‬
‭ ‭Backslash‬

\'‬
‭ ‭Single quote‬

\"‬
‭ ‭Double quote‬

‭6.4 String Methods‬


‭●‬ ‭Python has‬‭lots of built-in string methods‬‭.‬

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!']‬

print(" ".join(["Python", "is", "Legend"])) # Python is Legend‬


‭Exercise 6.1 – String Basics‬


‭58‬

‭1.‬ ‭Create a string‬‭


"Python Rocks!"‬‭and print it in‬‭uppercase‬‭and‬‭lowercase‬‭.‬

‭2.‬ ‭Slice‬‭
"PythonRocks"‬‭to get only‬‭ ‭.‬
"Rocks"‬

‭3.‬ ‭Count how many times‬‭


"o"‬‭appears in‬‭ ‭.‬
"Python is Good"‬

‭4.‬ ‭Replace‬‭
"Good"‬‭with‬‭ ‭.‬
"Legendary"‬

‭5.‬ ‭Remove extra spaces from‬‭ ‭.‬


" Python "‬

‭6.5 String Formatting‬


‭●‬ ‭Python has multiple ways to‬‭format strings‬‭.‬

‭6.5.1 Using f-strings (Python 3.6+)‬


name = "Akarsh"‬

age = 20‬

print(f"My name is {name} and I am {age} years old.")‬



‭59‬

‭Output:‬

My name is Akarsh and I am 20 years old.‬


‭6.5.2 Using format()‬


print("My name is {} and I am {} years old.".format(name, age))‬

‭6.5.3 Using % Operator‬


print("My name is %s and I am %d years old." % (name, age))‬

‭60‬

‭6.6 String Escape Sequences‬


‭●‬ ‭Multi-line strings using‬‭
''' '''‬‭or‬‭
""" """‬

multi_line = """This is Python‬


It is powerful‬

It is easy to learn"""‬

print(multi_line)‬

‭61‬

‭Output:‬

This is Python‬

It is powerful‬

It is easy to learn‬

‭6.7 String Indexing Tricks‬


‭●‬ ‭Reverse string:‬
‭62‬

text = "Python"‬

print(text[::-1])
‭ # nohtyP‬

‭●‬ ‭Check palindrome:‬

word = "level"‬

if word == word[::-1]:‬

print("Palindrome")‬

‭63‬

else:‬

print("Not Palindrome")‬

‭6.8 String Validation Methods‬


‭Method‬ ‭Meaning‬ ‭Example‬ ‭Output‬

‭isaln‬ ‭Only letters & numbers‬


. ‭Python3".isal‬ ‭True‬
"
um()‬
‭ num()‬

‭64‬

‭isalp‬ ‭Only letters‬


. ‭Python".isalp‬ ‭True‬
"
ha()‬
‭ ha()‬

‭isdig‬ ‭Only digits‬


. ‭123".isdigit(‬ ‭True‬
"
it()‬
‭ )‬

‭islow‬ ‭All lowercase‬


. ‭python".islow‬ ‭True‬
"
er()‬
‭ er()‬

‭isupp‬ ‭All uppercase‬


. ‭PYTHON".isupp‬ ‭True‬
"
er()‬
‭ er()‬

‭isspa‬ ‭Only spaces‬


. " ".isspace()‬
‭ ‭True‬
ce()‬

‭65‬

‭Exercise 6.2 – String Methods‬

‭1.‬ ‭Check if‬‭


"Python3"‬‭is alphanumeric.‬

‭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.‬

‭5.‬ ‭Check if‬‭


"123"‬‭contains only digits.‬

‭6.9 Mini Project 6 – Text Analyzer‬


‭Goal:‬‭Analyze a paragraph of text.‬

‭●‬ ‭Input a paragraph.‬

‭●‬ ‭Output:‬

‭1.‬ ‭Number of words‬

‭2.‬ ‭Number of characters‬

‭3.‬ ‭Number of sentences‬

‭4.‬ ‭Count of each vowel‬


‭66‬

text = input("Enter a paragraph: ")‬


# Number of characters‬

chars = len(text)‬

# Number of words‬

words = len([Link]())‬

‭67‬

# Number of sentences‬

sentences = [Link]('.') + [Link]('!') + [Link]('?')‬


# Count vowels‬

vowels = 'aeiouAEIOU'‬

vowel_count = {v: [Link](v) for v in vowels}‬



‭68‬

print(f"Characters: {chars}")‬

print(f"Words: {words}")‬

print(f"Sentences: {sentences}")‬

print(f"Vowels count: {vowel_count}")‬


‭✅‬‭Chapter 6 Summary‬
‭69‬

‭●‬ ‭Strings store‬‭text data‬‭.‬

‭●‬ ‭Access via‬‭indexing & slicing‬‭.‬

‭●‬ ‭Strings are‬‭immutable‬‭.‬

‭●‬ ‭Use‬‭methods‬‭to manipulate strings.‬

‭●‬ ‭Formatting strings‬‭makes outputs clean.‬

‭●‬ ‭Mini projects help‬‭real-life applications‬‭.‬


‭70‬

‭📖 Chapter 7: Python Conditional Statements & Loops – Making‬


‭Decisions & Repeating Actions‬

‭7.1 Introduction‬
‭●‬ ‭Python programs often need to‬‭make decisions‬‭or‬‭repeat‬‭actions‬‭.‬

‭●‬ ‭Conditional statements let your program‬‭choose a path‬‭.‬

‭●‬ ‭Loops let your program‬‭repeat tasks efficiently‬‭.‬

‭Think of it like:‬

"‭ If it’s raining, take umbrella, else enjoy the sun." 🌦️‬
‭"Do push-ups 10 times, repeat daily." 💪‬

‭7.2 Conditional Statements (‬‭ ‭,‬‭


if‬ ‭,‬‭
elif‬ ‭)‬
else‬

‭Syntax:‬
if condition1:‬

‭71‬

# do something‬

elif condition2:‬

# do something else‬

else:‬

# default action‬

‭Example 1: Age Checker‬


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

‭72‬

if age < 18:‬


print("You are a minor!")‬


elif age < 60:‬


print("You are an adult!")‬


else:‬

print("You are a senior citizen!")‬


‭Logical Operators‬
‭73‬

‭●‬ ‭ ‭,‬‭
and‬ ‭,‬‭
or‬ not‬‭for complex conditions:‬

x = 10‬

y = 5‬

if x > 5 and y > 2:‬


print("Both conditions are True!")‬


‭Exercise 7.1 – Conditionals‬

‭1.‬ ‭Input a number, print if‬‭positive, negative, or zero‬‭.‬


‭74‬

‭2.‬ ‭Input marks (0-100), print‬‭grade‬‭:‬

‭○‬ ‭90-100 → A‬

‭○‬ ‭75-89 → B‬

‭○‬ ‭50-74 → C‬

‭○‬ ‭<50 → F‬

‭3.‬ ‭Input a character, print if‬‭vowel or consonant‬‭.‬

‭4.‬ ‭Input‬‭three numbers‬‭, print the‬‭largest‬‭.‬

‭7.3 Loops in Python‬


‭Python has‬‭two main loops‬‭:‬

‭1.‬ ‭
for‬‭loop‬‭→ iterate over a sequence (list, string,‬‭range).‬

‭2.‬ ‭
while‬‭loop‬‭→ repeat‬‭while a condition is True‬‭.‬

‭7.3.1‬‭
for‬‭Loop‬
‭75‬

# Example: Print numbers 1 to 5‬


for i in range(1, 6):‬


print(i)‬

# Example: Loop over a string‬


word = "Python"‬

for letter in word:‬



‭76‬

print(letter)‬

‭Exercise 7.2 – For Loop‬

‭1.‬ ‭Print numbers from‬‭10 to 1‬‭in reverse.‬

‭2.‬ ‭Print‬‭all even numbers‬‭between 1–50.‬

‭3.‬ ‭Print each character of your‬‭name‬‭in a new line.‬

‭4.‬ ‭Print‬‭squares of numbers‬‭from 1 to 10.‬

‭7.3.2‬‭
while‬‭Loop‬
# Example: Counting down‬

count = 5‬

‭77‬

while count > 0:‬


print(count)‬

count -= 1‬

‭●‬ ‭Infinite loop warning:‬‭Make sure‬‭condition becomes‬‭False‬‭eventually!‬

# Avoid infinite loop‬


i = 0‬

‭78‬

while i < 5:‬


print(i)‬

i += 1‬

‭7.3.3 Loop Control Statements‬


‭Statement‬ ‭Purpose‬ ‭Example‬
‭79‬

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‬

for i in range(1, 11):‬


if i == 5:‬

break
‭ # stops the loop‬

print(i)‬

‭80‬

for i in range(1, 6):‬


if i == 3:‬

continue
‭ # skips 3‬

print(i)‬

‭Exercise 7.3 – While & Control Statements‬


‭81‬

‭1.‬ ‭Print numbers‬‭1 to 20‬‭using‬‭ ‭.‬


while‬

‭2.‬ ‭Print numbers‬‭1 to 10‬‭, skip‬‭multiples of 3‬‭.‬

‭3.‬ ‭Input numbers until‬‭user enters 0‬‭, then print‬‭sum‬‭.‬

‭4.‬ ‭Loop over‬‭ ‭, stop at letter‬‭


"Python"‬ ‭.‬
"h"‬

‭7.4 Nested Loops‬


‭●‬ ‭Loop inside a loop.‬

# Print multiplication table‬


for i in range(1, 6):‬


for j in range(1, 6):‬



‭82‬

print(i*j, end="\t")‬

print()‬

‭●‬ ‭Output:‬‭Multiplication table 1–5‬

‭Exercise 7.4 – Nested Loops‬

‭1.‬ ‭Print‬‭triangle pattern‬‭:‬

*‬

**‬

***‬

‭83‬

****‬

‭2.‬ ‭Print‬‭reverse triangle‬‭:‬

****‬

***‬

**‬

*‬

‭84‬

‭3.‬ ‭Print‬‭multiplication table‬‭of 1–10 in grid format.‬

‭7.5 Practical Mini Project 7 – Number Guessing Game‬


‭Goal:‬‭Create a game where the user guesses a random‬‭number.‬

import random‬

number = [Link](1, 20)‬


guess = None‬

‭85‬

while guess != number:‬


guess = int(input("Guess the number (1-20): "))‬


if guess < number:‬


print("Too low!")‬

elif guess > number:‬


print("Too high!")‬

‭86‬

else:‬

print("Congratulations! You guessed it!")‬


‭●‬ ‭Concepts used:‬‭while loop, if-elif-else, random module,‬‭user input‬

‭7.6 Chapter Summary‬


‭●‬ ‭Conditional statements:‬‭if, elif, else → make decisions.‬

‭●‬ ‭Loops:‬‭for & while → repeat tasks efficiently.‬

‭●‬ ‭Loop controls:‬‭break, continue, pass → control flow‬‭inside loops.‬

‭●‬ ‭Nested loops:‬‭used for patterns, tables, complex iterations.‬


‭87‬

‭📖 Chapter 8: Python Functions – Organizing Code Like a Pro‬

‭8.1 Introduction‬
‭●‬ ‭Functions are‬‭reusable blocks of code‬‭.‬

‭●‬ ‭Agar tu baar-baar same code likhega → waste of time.‬

‭●‬ ‭Functions‬‭organize, simplify, and structure‬‭your program.‬

‭ 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.”‬‭🧼‬

‭8.2 Defining a Function‬

‭Syntax‬
def function_name(parameters):‬

‭88‬

"""docstring: explains what function does"""‬


# code block‬

return value‬

def‬‭→ defines a function‬


‭●‬ ‭

parameters‬‭→ inputs for the function‬


‭●‬ ‭

return‬‭→ output of the function‬


‭●‬ ‭

‭Example 1: Simple Function‬


def greet():‬

‭89‬

print("Hello, Brother! Welcome to Python!")‬


greet()‬

‭●‬ ‭Output:‬‭
Hello, Brother! Welcome to Python!‬

‭●‬ ‭No parameters, no return → just prints a message‬

‭Example 2: Function with Parameters‬


def greet_user(name):‬

‭90‬

print(f"Hello, {name}! Welcome to Python!")‬


greet_user("Akarsh")‬

‭●‬ ‭Output:‬‭
Hello, Akarsh! Welcome to Python!‬

‭●‬ ‭Functions can‬‭take input dynamically‬

‭Example 3: Function with Return Value‬


def add(a, b):‬

‭91‬

return a + b‬

result = add(5, 3)‬


print("Sum:", result)‬

‭●‬ ‭Output:‬‭
Sum: 8‬

return‬‭allows‬‭using the output elsewhere‬


‭●‬ ‭

‭8.3 Types of Functions‬


‭92‬

‭1.‬ ‭Built-in Functions‬‭→ Already in Python (e.g.,‬‭ ‭,‬‭


print()‬ ‭,‬‭
len()‬ ‭)‬
input()‬

‭2.‬ ‭User-Defined Functions‬‭→ We create (like above)‬

‭3.‬ ‭Anonymous Functions (Lambda)‬‭→ One-line functions‬

square = lambda x: x**2‬


print(square(5))
‭ # Output: 25‬

‭8.4 Function Arguments‬

‭8.4.1 Positional Arguments‬


def greet(name, age):‬

‭93‬

print(f"{name} is {age} years old")‬


greet("Akarsh", 20)‬

‭8.4.2 Keyword Arguments‬


greet(age=20, name="Akarsh")‬

‭8.4.3 Default Arguments‬


‭94‬

def greet(name="Brother"):‬

print(f"Hello, {name}!")‬

greet()
‭ # Hello, Brother!‬

greet("Akarsh")
‭ # Hello, Akarsh!‬

‭8.4.4 Variable-Length Arguments (‬‭ ‭,‬‭


*args‬ ‭)‬
**kwargs‬
def add_numbers(*args):‬

‭95‬

return sum(args)‬

print(add_numbers(1, 2, 3, 4))
‭ # Output: 10‬

def show_info(**kwargs):‬

for key, value in [Link]():‬


print(key, ":", value)‬



‭96‬

show_info(name="Akarsh", age=20)‬

‭8.5 Scope of Variables‬


‭●‬ ‭Local variable:‬‭defined inside function, only accessible‬‭inside‬

‭●‬ ‭Global variable:‬‭defined outside, accessible everywhere‬

x = 10
‭ # global‬
‭97‬

def func():‬

y = 5
‭ # local‬

print("Inside:", x + y)‬

func()‬

print("Outside:", x)
‭ # y is not accessible‬
‭98‬

‭8.6 Recursion (Advanced)‬


‭●‬ ‭Function calling‬‭itself‬‭→ recursion‬

‭●‬ ‭Must have‬‭base case‬‭, else infinite loop‬

def factorial(n):‬

if n == 0 or n == 1:‬

return 1‬

else:‬

return n * factorial(n-1)‬

‭99‬

print(factorial(5))
‭ # Output: 120‬

‭Exercise 8.1 – Functions‬

‭1.‬ ‭Create a function to‬‭check if a number is prime‬‭.‬

‭2.‬ ‭Function to‬‭calculate area of rectangle‬‭(length, breadth).‬

‭3.‬ ‭Function with‬‭default argument‬‭to greet user.‬

‭4.‬ ‭Function to‬‭reverse a string‬‭using return.‬

‭5.‬ ‭Function using‬‭variable-length arguments‬‭to return‬‭max number‬‭.‬


‭100‬

‭Mini Project 8 – Calculator Using Functions‬

‭Goal:‬‭Build a simple calculator with‬‭functions for‬‭add, subtract, multiply, divide‬‭.‬

def add(a, b):‬


return a + b‬

def subtract(a, b):‬


return a - b‬

‭101‬

def multiply(a, b):‬


return a * b‬

def divide(a, b):‬


if b != 0:‬

return a / b‬

else:‬

‭102‬

return "Cannot divide by zero"‬


print("Select operation: add, subtract, multiply, divide")‬


choice = input("Enter choice: ")‬


num1 = float(input("Enter first number: "))‬


num2 = float(input("Enter second number: "))‬



‭103‬

if choice == "add":‬

print(add(num1, num2))‬

elif choice == "subtract":‬


print(subtract(num1, num2))‬

elif choice == "multiply":‬


print(multiply(num1, num2))‬

‭104‬

elif choice == "divide":‬


print(divide(num1, num2))‬

else:‬

print("Invalid choice")‬

‭8.7 Chapter Summary‬


‭●‬ ‭Functions‬‭: reusable code blocks‬

‭●‬ ‭Parameters & Arguments‬‭: inputs to functions‬


‭105‬

‭●‬ ‭Return‬‭: outputs from functions‬

‭●‬ ‭Variable-length arguments‬‭: handle multiple inputs‬

‭●‬ ‭Scope‬‭: local vs global variables‬

‭●‬ ‭Recursion‬‭: function calls itself (base case needed)‬

‭●‬ ‭Mini Project: simple‬‭calculator using functions‬


‭106‬

‭📖 Chapter 9: Python Modules & Packages – Building Your Own‬


‭Libraries‬

‭9.1 Introduction‬
‭●‬ J‭ust like functions are used for‬‭code reuse‬‭,‬‭modules‬‭and packages‬‭help organize‬
‭large programs‬‭.‬

‭●‬ ‭Module‬‭→ a Python file containing functions, variables,‬‭or classes.‬

‭●‬ ‭Package‬‭→ a folder containing multiple modules.‬

‭ hink of functions as‬‭tools‬‭, and modules & packages‬‭as‬‭toolboxes and‬


T
‭warehouses‬‭. 🛠️‬

‭9.2 Python Modules‬


‭●‬ ‭Python has many‬‭built-in modules‬‭like‬‭ ‭,‬‭
math‬ ‭,‬‭and‬‭
random‬ ‭.‬
os‬

‭●‬ ‭You can also create‬‭custom modules‬‭.‬

‭Creating a Custom Module‬

‭File:‬‭
[Link]‬

def greet(name):‬

return f"Hello, {name}!"‬

def add(a, b):‬



return a + b‬

‭107‬

‭File:‬‭
[Link]‬

import mymodule‬

print([Link]("Akarsh"))‬

print([Link](5, 7))‬

‭Output:‬

Hello, Akarsh!‬

12‬

‭9.2.1 Import Variants‬

‭1.‬ ‭Simple import‬

import math‬

print([Link](16))‬

‭2.‬ ‭Import specific function‬

from math import sqrt‬



print(sqrt(25))‬

‭3.‬ ‭Import with alias‬

import math as m‬

print([Link](5))‬

‭108‬

‭9.3 Python Packages‬


‭●‬ ‭A‬‭package‬‭is a folder containing multiple modules‬‭plus an‬‭
__init__.py‬‭file.‬

__init__.py‬‭tells Python that this folder is a package.‬


‭●‬ ‭

‭Structure:‬

mypackage/‬

__init__.py‬

[Link]‬

[Link]‬

‭Usage:‬

from mypackage import module1‬



[Link]()‬

‭9.3.1 Example Package: MathTools‬

‭Folder Structure:‬

MathTools/‬

__init__.py‬

[Link]‬

[Link]‬

‭[Link]‬
‭109‬

def add(a, b):‬



return a + b‬

def subtract(a, b):‬



return a - b‬

‭[Link]‬

def area_rectangle(length, breadth):‬



return length * breadth‬

def area_circle(radius):‬

import math‬

return [Link] * radius ** 2‬

‭[Link]‬

from MathTools import arithmetic, geometry‬


print([Link](10, 5))
‭ # 15‬
print(geometry.area_circle(7))
‭ # 153.938...‬

‭9.4 Built-in Useful Modules‬


‭1.‬ ‭math‬‭→ mathematical operations‬

‭2.‬ ‭random‬‭→ generate random numbers‬

‭3.‬ ‭datetime‬‭→ work with dates & time‬


‭110‬

‭4.‬ ‭os‬‭→ operating system tasks‬

‭5.‬ ‭sys‬‭→ system operations‬

‭6.‬ ‭json‬‭→ work with JSON data‬

‭Example:‬

import random‬

print([Link](1, 100))
‭ # Random number between 1-100‬

‭9.5 Installing External Modules (pip)‬


‭●‬ ‭To use extra libraries, Python uses‬‭ ‭.‬
pip‬

pip install requests‬


‭Example using‬‭ ‭:‬


requests‬

import requests‬

response = [Link]("[Link]

print(response.status_code)‬

print([Link]())‬

‭●‬ ‭This allows you to interact with real-world APIs.‬

‭9.6 Exercises‬
‭111‬

‭1.‬ ‭Create a module‬‭


[Link]‬‭with functions:‬‭
hello(name)‬‭and‬‭
goodbye(name)‬

‭2.‬ ‭Create a package‬‭


MyMath‬‭with modules‬‭
[Link]‬‭and‬‭
[Link]‬

‭3.‬ ‭Use the built-in module‬‭


random‬‭to generate a list‬‭of 10 random numbers‬

‭4.‬ ‭Use‬‭
datetime‬‭to print the current date and time‬

‭5.‬ ‭Install‬‭
requests‬‭and make a request to a public API‬‭like GitHub‬

‭9.7 Mini Project 9 – Personal Library‬


‭Goal:‬‭Build a small‬‭personal library package‬

‭Folder Structure:‬

MyLibrary/‬

__init__.py‬

[Link]‬

[Link]‬

‭[Link]‬

books = []‬

def add_book(title, author):‬



[Link]({"title": title, "author": author})‬

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]‬

from MyLibrary import books, members‬


books.add_book("Python Mastery", "Akarsh")‬



books.add_book("AI Guide", "OpenAI")‬

members.add_member("Akarsh")‬

members.add_member("Brother")‬

books.show_books()‬

members.show_members()‬

‭Output:‬

Python Mastery by Akarsh‬



AI Guide by OpenAI‬

Akarsh‬

Brother‬

‭113‬

‭ his demonstrates how you can‬‭structure reusable code using modules and‬
T
‭packages‬‭.‬

‭9.8 Summary‬
‭●‬ ‭Module:‬‭single Python file with reusable functions/classes‬

‭●‬ ‭Package:‬‭folder containing modules‬

‭●‬ ‭Import styles:‬‭simple, specific, alias‬

‭●‬ ‭Built-in modules:‬‭math, random, datetime, os, sys,‬‭json‬

‭●‬ ‭External modules:‬‭install via pip for real-world applications‬

‭●‬ ‭Mini Project: Personal library system using‬‭modules and packages‬


‭114‬

‭📖 Chapter 10: Python File Handling – Reading & Writing Files‬

‭10.1 Introduction‬
‭●‬ ‭Files are used to‬‭store data permanently‬‭.‬

‭●‬ ‭Unlike variables which store data temporarily (in memory),‬‭files save data on disk‬‭.‬

‭●‬ ‭Python allows you to‬‭read, write, and append files‬‭easily.‬

‭ hink of files as‬‭notebooks‬‭. You can write new notes,‬‭read existing ones, or‬
T
‭add more notes at the end.‬

‭10.2 File Modes‬


‭Python uses‬‭modes‬‭to open files:‬

‭Mode‬ ‭Description‬

'r'‬
‭ ‭Read (default) – file must exist‬

'w'‬
‭ ‭Write – creates file or overwrites‬

'a'‬
‭ ‭Append – adds to the end of file‬

'r+'‬ ‭Read and write‬


'b'‬
‭ ‭Binary mode (e.g.,‬‭
'rb'‬‭or‬‭ ‭)‬
'wb'‬

‭10.3 Opening & Closing Files‬


‭115‬

# Open a file in read mode‬


file = open("[Link]", "r")‬


# Do operations‬

content = [Link]()‬

print(content)‬

# Close the file‬



[Link]()‬

‭Tip:‬‭Always close a file to‬‭save memory and avoid‬‭errors‬‭.‬

‭10.4 Using‬‭
with‬‭Statement (Recommended)‬
with open("[Link]", "r") as file:‬

content = [Link]()‬

print(content)‬

# No need to explicitly close the file‬

with‬‭automatically‬‭closes the file‬‭when done.‬


‭10.5 Reading Files‬


‭1.‬ ‭Read entire file‬

with open("[Link]", "r") as file:‬



data = [Link]()‬

print(data)‬

‭116‬

‭2.‬ ‭Read line by line‬

with open("[Link]", "r") as file:‬



for line in file:‬

print([Link]())‬

‭3.‬ ‭Read specific number of characters‬

with open("[Link]", "r") as file:‬



print([Link](10))
‭ # Reads first 10 characters‬

‭10.6 Writing to Files‬


‭1.‬ ‭Write Mode (‬‭
w‭)‬‬

with open("[Link]", "w") as file:‬



[Link]("Hello Python!\n")‬

[Link]("File handling is fun!")‬

‭●‬ ‭Overwrites existing content.‬

‭2.‬ ‭Append Mode (‬‭


a‬‭)‬

with open("[Link]", "a") as file:‬



[Link]("\nAdding a new line at the end.")‬

‭117‬

‭10.7 File Functions‬


[Link]()‬‭→ Reads entire content‬
‭●‬ ‭

[Link]()‬‭→ Reads one line at a time‬


‭●‬ ‭

[Link]()‬‭→ Returns all lines as a list‬


‭●‬ ‭

[Link](text)‬‭→ Writes text‬


‭●‬ ‭

[Link](pos)‬‭→ Move cursor to position‬


‭●‬ ‭

[Link]()‬‭→ Returns current cursor position‬


‭●‬ ‭

‭10.8 Working with Binary Files‬


# Writing an image in binary mode‬

with open("[Link]", "rb") as img:‬



data = [Link]()‬

print(len(data))‬

‭●‬ ‭Useful for images, videos, or any non-text data.‬

‭10.9 Exercises‬
‭1.‬ ‭Create a file‬‭
[Link]‬‭and write your‬‭name, age,‬‭and favorite language‬‭.‬

‭2.‬ ‭Read the file and‬‭print each line‬‭separately.‬

‭3.‬ ‭Append a‬‭new hobby‬‭to the file.‬


‭118‬

‭4.‬ C
‭ reate a‬‭file containing numbers from 1 to 50‬‭, then‬‭read it and print‬‭only even‬
‭numbers‬‭.‬

‭5.‬ ‭Read a binary file (image or PDF) and print its‬‭size‬‭in bytes‬‭.‬

‭10.10 Mini Project 10 – To-Do List App‬


‭Goal:‬‭Build a simple‬‭command-line to-do list‬‭that‬‭stores tasks in a file.‬

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 can‬‭keep adding tasks‬‭, and they will be saved‬‭permanently in‬‭ ‭.‬
[Link]‬

‭10.11 Summary‬
‭●‬ ‭Python files allow‬‭permanent storage of data‬‭.‬

‭●‬ ‭Always‬‭open files in the correct mode‬‭(‭


‬‬
r‭,‬‭
w‭,‬‬‭‭).‬
a‬

‭●‬ ‭Use‬‭
with‬‭for‬‭automatic closing‬‭.‬

‭●‬ ‭File operations:‬‭ ‭,‬‭


read()‬ ‭,‬‭
readline()‬ ‭,‬‭
readlines()‬ ‭,‬‭
write()‬ ‭,‬‭
seek()‬ tell()‬

‭●‬ ‭Binary mode is for‬‭non-text data‬‭.‬

‭●‬ ‭Mini Project: To-Do list shows‬‭real-world usage‬‭of file handling.‬


‭120‬

‭📖 Chapter 11: Python Exception Handling – Errors & Debugging‬

‭11.1 Introduction‬
‭●‬ ‭In programming, sometimes‬‭errors occur‬‭during execution.‬

‭●‬ ‭These errors are called‬‭exceptions‬‭.‬

‭●‬ P
‭ ython provides a‬‭way to catch and handle errors‬‭using‬‭try, except, else, and‬
‭finally‬‭blocks.‬

‭ hink of it like‬‭driving a car‬‭: you put a seatbelt,‬‭check brakes, and have airbags.‬
T
‭Errors might happen, but you can handle them safely.‬

‭11.2 Common Python Exceptions‬

‭Exception‬ ‭Meaning‬

‭eroDivisionE‬ ‭Dividing by zero‬


Z
rror‬

‭ileNotFoundE‬ ‭File does not exist‬


F
rror‬

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‬

‭11.3 Try & Except‬


try:‬

x = 10 / 0‬

except ZeroDivisionError:‬

print("Cannot divide by zero!")‬

try‬‭block → code that may produce an error‬


‭●‬ ‭

except‬‭block → handle the error‬


‭●‬ ‭

‭11.4 Catching Multiple Exceptions‬


try:‬

x = int(input("Enter a number: "))‬



y = 10 / x‬

except ZeroDivisionError:‬

print("Cannot divide by zero!")‬

except ValueError:‬

print("Invalid input! Enter a number.")‬

‭●‬ ‭Can catch‬‭different errors‬‭separately.‬

‭11.5 Using Else‬


try:‬

‭122‬

num = int(input("Enter a number: "))‬



except ValueError:‬

print("Invalid input!")‬

else:‬

print("You entered:", num)‬

else‬‭runs‬‭only if no exception occurs‬‭.‬


‭●‬ ‭

‭11.6 Finally Block‬


try:‬

file = open("[Link]", "r")‬



except FileNotFoundError:‬

print("File not found!")‬

finally:‬

print("Execution finished.")‬

finally‬‭always executes‬‭, even if error occurs.‬


‭●‬ ‭

‭●‬ ‭Useful for‬‭closing files, releasing resources‬‭.‬

‭11.7 Raising Exceptions‬


‭●‬ ‭Sometimes, we want to‬‭manually raise an exception‬‭.‬

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



if age < 0:‬

‭123‬

raise ValueError("Age cannot be negative!")‬


‭●‬ ‭Use‬‭
raise‬‭to‬‭force an error‬‭if condition is invalid.‬

‭11.8 Custom Exceptions‬


class TooYoungError(Exception):‬

pass‬

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



if age < 18:‬

raise TooYoungError("You are too young!")‬

‭●‬ ‭Can create‬‭custom error messages‬‭for clarity.‬

‭11.9 Exercises‬
‭1.‬ ‭Write a program to‬‭divide two numbers‬‭, handle‬‭ ‭.‬
ZeroDivisionError‬

‭2.‬ ‭Input a number from user, handle‬‭


ValueError‬‭if input‬‭is invalid.‬

‭3.‬ ‭Open a file and handle‬‭ ‭.‬


FileNotFoundError‬

‭4.‬ ‭Create a program to access a‬‭list element‬‭, handle‬‭ ‭.‬


IndexError‬

‭5.‬ ‭Write a program to raise a‬‭custom exception‬‭if user‬‭enters negative number.‬


‭124‬

‭11.10 Mini Project 11 – Safe Calculator‬


‭Goal:‬‭Build a‬‭calculator that won’t crash‬‭if wrong‬‭input is given.‬

def safe_divide(a, b):‬



try:‬

result = a / b‬

except ZeroDivisionError:‬

return "Error: Cannot divide by zero!"‬

except TypeError:‬

return "Error: Invalid input type!"‬

else:‬

return result‬

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!‬

‭●‬ ‭Handles‬‭multiple exceptions‬‭without crashing.‬

‭11.11 Summary‬
‭125‬

‭●‬ ‭Exceptions =‬‭errors during execution‬

try‬‭→ risky code‬


‭●‬ ‭

except‬‭→ handle error‬


‭●‬ ‭

else‬‭→ runs if no error‬


‭●‬ ‭

finally‬‭→ always runs‬


‭●‬ ‭

raise‬‭→ manually throw error‬


‭●‬ ‭

‭●‬ ‭Custom exceptions =‬‭user-defined error messages‬

‭●‬ ‭Exception handling makes‬‭programs safe and robust‬


‭126‬

‭📖 Chapter 12: Python Modules & Packages – Organizing Code‬

‭12.1 Introduction‬
‭●‬ ‭As your Python programs grow,‬‭all code in a single‬‭file becomes messy‬‭.‬

‭●‬ ‭To solve this, Python provides‬‭Modules‬‭and‬‭Packages‬‭to organize code.‬

‭●‬ ‭Think of it like‬‭books in a library‬‭:‬

‭○‬ ‭Each book = a‬‭module‬‭(contains related content)‬

‭○‬ ‭Shelf = a‬‭package‬‭(collection of modules)‬

‭12.2 What is a Module?‬


‭●‬ ‭A‬‭module‬‭is a‬‭Python file (.py)‬‭containing functions,‬‭classes, or variables.‬

‭●‬ ‭You can‬‭reuse‬‭this code in other programs using‬‭ ‭.‬


import‬

‭Example: math module (built-in)‬

import math‬

print([Link](16))
‭ # Output: 4.0‬
print([Link])
‭ # Output: 3.141592653589793‬

‭●‬ ‭You can also create your‬‭own module‬‭:‬


‭127‬

‭my_module.py‬

def greet(name):‬

return f"Hello, {name}!"‬

def add(a, b):‬



return a + b‬

‭[Link]‬

import my_module‬

print(my_module.greet("Akarsh"))‬

print(my_module.add(5, 7))‬

‭12.3 Importing Modules‬


‭Ways to import modules:‬

‭1.‬ ‭Import entire module‬

import random‬

print([Link](1, 10))‬

‭2.‬ ‭Import specific function‬

from math import sqrt, pi‬



print(sqrt(25))‬

print(pi)‬

‭128‬

‭3.‬ ‭Import with alias‬

import numpy as np‬



print([Link]([1,2,3]))‬

‭12.4 Standard Python Modules‬


‭●‬ ‭Python comes with‬‭many built-in modules‬‭:‬

‭Module‬ ‭Purpose‬

‭math‬ ‭Mathematical functions‬

‭random‬ ‭Random numbers‬

‭datetime‬ ‭Date & Time operations‬

‭os‬ ‭Operating system operations‬

‭sys‬ ‭Python interpreter functions‬

‭json‬ ‭Working with JSON data‬

‭re‬ ‭Regular expressions‬

‭12.5 What is a Package?‬


‭●‬ A
‭ ‬‭package‬‭is a‬‭folder containing multiple modules‬‭and a special file‬
__init__.py‬
‭ ‭.‬
‭129‬

‭●‬ ‭It helps to‬‭organize large projects‬‭.‬

‭Example structure:‬

my_project/‬

│‬

├── utils/‬


‭ ├── __init__.py‬

‭ ├── file_ops.py‬

‭ └── math_ops.py‬
│‬

└── [Link]‬

‭Using a module from a package‬

from utils.math_ops import add, subtract‬


print(add(5,3))‬

print(subtract(10,4))‬

‭12.6 Creating Your Own Package‬


‭1.‬ ‭Create folder‬‭
my_package‬

‭2.‬ ‭Add‬‭
__init__.py‬‭(can be empty)‬

‭3.‬ ‭Add modules inside, e.g.,‬‭


math_ops.py‬

‭math_ops.py‬

def add(a, b):‬



‭130‬

return a + b‬

def multiply(a, b):‬



return a * b‬

‭[Link]‬

from my_package.math_ops import add, multiply‬


print(add(5,6))‬

print(multiply(4,7))‬

‭12.7 Advantages of Modules & Packages‬


‭●‬ ‭Code Reusability‬‭– write once, use many times‬

‭●‬ ‭Organization‬‭– makes large projects manageable‬

‭●‬ ‭Namespace Management‬‭– avoids variable conflicts‬

‭●‬ ‭Readability‬‭– easier to understand‬

‭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‬‭ shapes‬‭with modules‬‭
[Link]‬‭and‬‭ ‭. Implement‬
[Link]‬
‭area calculation in both.‬

‭4.‬ ‭Use‬‭
random‬‭module to simulate a‬‭dice roll‬‭.‬

‭5.‬ ‭Use‬‭
datetime‬‭module to print‬‭current date and time‬‭.‬

‭12.9 Mini Project 12 – Mini Library System‬


‭Goal:‬‭Organize a small‬‭book library program‬‭using‬‭modules and packages.‬

‭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]‬

from [Link] import add_book, list_books‬



from [Link] import add_user, list_users‬

add_book("Python Mastery")‬

add_user("Akarsh")‬

print(list_books())‬

print(list_users())‬

‭Output:‬

['Python Mastery']‬

['Akarsh']‬

‭●‬ ‭Shows‬‭how modules & packages organize real projects‬‭.‬

‭12.10 Summary‬
‭133‬

‭●‬ ‭Modules‬‭= single file with reusable code‬

‭●‬ ‭Packages‬‭= folder with multiple modules‬

‭●‬ ‭Import modules using‬‭ ‭,‬‭


import‬ ‭, or alias‬
from … import‬

‭●‬ ‭Use standard library modules to‬‭save time‬

‭●‬ ‭Custom modules & packages make projects‬‭scalable and clean‬


‭134‬

‭📖 Chapter 13: Python File Handling – Reading & Writing Files‬

‭13.1 Introduction‬
‭ hen we write a Python program, all the data exists‬‭only in memory‬‭while the program is‬
W
‭running.‬
‭Once the program ends, all the memory data disappears.‬

‭ o solve this, we use‬‭files‬‭. Files allow us to‬‭store‬‭data permanently‬‭so it can be accessed‬


T
‭later, even after the program stops.‬

‭Types of Files in Python:‬

‭1.‬ ‭Text Files (.txt)‬‭– readable by humans, contains plain‬‭text‬

‭2.‬ B
‭ inary Files (.bin, .jpg, .png)‬‭– contains non-text‬‭data like images, videos, or other‬
‭formats‬

‭Files are essential for applications like contact books, logs, data storage, and more.‬

‭13.2 Opening a File‬


‭Python uses the‬‭
open()‬‭function‬‭to work with files.‬

‭Syntax:‬

file = open("[Link]", "mode")‬


‭File Modes:‬

‭Mode‬ ‭Meaning‬

‭"r"‬ ‭Read (default)‬


‭135‬

‭"w"‬ ‭Write (overwrite if file exists)‬

‭"a"‬ ‭Append (add data at the end)‬

‭"x"‬ ‭Create new file, error if already exists‬

‭"rb"‬ ‭Read binary data‬

‭"wb"‬ ‭Write binary data‬


‭Example: Writing to a file‬

file = open("[Link]", "w")‬



[Link]("Hello, Python File Handling!")‬

[Link]()‬

‭13.3 Reading a File‬


‭Read entire file content‬

file = open("[Link]", "r")‬



content = [Link]()‬

print(content)‬

[Link]()‬

‭Read line by line‬

file = open("[Link]", "r")‬



for line in file:‬

print([Link]())
‭ # Remove newline characters‬
[Link]()‬

‭136‬

‭Read a specific number of characters‬

file = open("[Link]", "r")‬



print([Link](5))
‭ # Reads first 5 characters‬
[Link]()‬

‭13.4 Writing to a File‬


‭●‬ ‭Overwrite existing content:‬

file = open("[Link]", "w")‬



[Link]("This will overwrite previous content.")‬

[Link]()‬

‭●‬ ‭Append content at the end:‬

file = open("[Link]", "a")‬



[Link]("\nThis text is added at the end.")‬

[Link]()‬

‭13.5 Using‬‭
with‬‭Statement (Best Practice)‬
‭The‬‭
with‬‭statement automatically closes the file when‬‭done.‬

‭Example:‬

with open("[Link]", "r") as file:‬



content = [Link]()‬

print(content)‬

‭137‬

‭Appending with‬‭ ‭:‬


with‬

with open("[Link]", "a") as file:‬



[Link]("\nThis is appended using 'with'.")‬

‭13.6 Binary Files‬


‭Binary files are used for‬‭non-text data‬‭like images,‬‭videos, or serialized objects.‬

‭Write binary data:‬

data = b"Python in bytes"‬



with open("[Link]", "wb") as file:‬

[Link](data)‬

‭Read binary data:‬

with open("[Link]", "rb") as file:‬



content = [Link]()‬

print(content)‬

‭13.7 Useful File Methods‬

‭Method‬ ‭Description‬

read()‬
‭ ‭Read the entire file‬

‭eadlin‬ ‭Read a single line‬


r
e()‬

‭138‬

‭eadlin‬ ‭Return a list of all lines‬


r
es()‬

write()‬ ‭Write a string to the file‬


‭riteli‬ ‭Write a list of strings‬


w
nes()‬

close()‬ ‭Close the file‬


‭13.8 Exercises‬
‭1.‬ ‭Create a file‬‭
[Link]‬‭and write names of 5 students.‬

‭2.‬ ‭Read‬‭
[Link]‬‭line by line and print names with‬‭line numbers.‬

‭3.‬ ‭Append 2 more names to‬‭ ‭.‬


[Link]‬

‭4.‬ ‭Read the first 10 characters of a file.‬

‭5.‬ ‭Create a binary file‬‭


[Link]‬‭and write some bytes.‬‭Then read it back.‬

‭13.9 Mini Project – Contact Book‬


‭Goal:‬‭Store contacts (name + phone number) in a text‬‭file and retrieve them.‬

‭[Link]‬

def add_contact(name, number):‬



with open("[Link]", "a") as file:‬

[Link](f"{name},{number}\n")‬

def list_contacts():‬

‭139‬

with open("[Link]", "r") as file:‬



for line in file:‬

name, number = [Link]().split(",")‬

print(f"Name: {name}, Number: {number}")‬

‭[Link]‬

from contacts import add_contact, list_contacts‬


add_contact("Akarsh", "9876543210")‬

add_contact("Riya", "9123456789")‬

list_contacts()‬

‭Expected Output:‬

Name: Akarsh, Number: 9876543210‬



Name: Riya, Number: 9123456789‬

‭13.10 Summary‬
‭●‬ ‭Files allow‬‭permanent data storage‬

‭●‬ ‭Key modes:‬‭ ‭,‬‭


"r"‬ ‭,‬‭
"w"‬ ‭,‬‭
"a"‬ ‭,‬‭
"x"‬ ‭,‬‭
"rb"‬ "wb"‬

‭●‬ ‭Always prefer the‬‭


with‬‭statement‬

‭●‬ ‭Binary files are for‬‭non-text data‬

‭●‬ U
‭ se file methods:‬‭ ‭,‬‭
read()‬ ‭,‬‭
readline()‬ ‭,‬‭
readlines()‬ ‭,‬‭
write()‬ ‭,‬
writelines()‬
close()‬

‭140‬

‭●‬ ‭Mini-projects reinforce‬‭real-world file handling‬

‭📖 Chapter 14: Python Exception Handling – Errors & Debugging Like a‬


‭Pro‬

‭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:‬

num = int(input("Enter a number: "))‬


print(10 / num)‬

‭●‬ ‭If user enters‬‭


0‭,‬the program crashes with a‬‭ ‭.‬
ZeroDivisionError‬

‭●‬ ‭If user enters‬‭ ‭, the program crashes with a‬‭


"abc"‬ ‭.‬
ValueError‬

‭ e need a way to handle errors gracefully so the program doesn’t crash. This is‬
W
‭where Exception Handling comes in.‬

‭14.2 What are Exceptions?‬


‭●‬ ‭Exceptions are runtime errors that occur while a program is running.‬

‭●‬ ‭Python has many built-in exceptions like:‬


‭141‬

‭Exception‬ ‭Cause‬

‭eroDivisionE‬ ‭Division by zero‬


Z
rror‬

ValueError‬
‭ ‭Invalid data type conversion‬

‭ileNotFoundE‬ ‭File doesn’t exist‬


F
rror‬

IndexError‬
‭ ‭Invalid index in a list‬

KeyError‬
‭ ‭Accessing missing key in dictionary‬

TypeError‬
‭ ‭Operation on incompatible types‬

‭14.3 Try and Except‬


‭The try-except block is used to catch exceptions.‬

‭Syntax:‬

try:‬

# code that may raise an exception‬


except ExceptionType:‬

# code to handle the exception‬


‭Example:‬

try:‬

num = int(input("Enter a number: "))‬



‭142‬

print(10 / num)‬

except ZeroDivisionError:‬

print("You cannot divide by zero!")‬


except ValueError:‬

print("Please enter a valid number!")‬


‭14.4 The Else Block‬


else‬‭runs only if no exception occurs.‬

try:‬

num = int(input("Enter a number: "))‬


result = 10 / num‬

except ZeroDivisionError:‬

print("Cannot divide by zero!")‬


except ValueError:‬

print("Invalid input!")‬

else:‬

print(f"Result is {result}")‬

‭14.5 The Finally Block‬


finally‬‭always runs no matter what, usually used for‬‭cleanup.‬

‭143‬

try:‬

file = open("[Link]", "r")‬


content = [Link]()‬

except FileNotFoundError:‬

print("File does not exist.")‬


finally:‬

print("This will always run.")‬


‭14.6 Raising Exceptions‬


‭You can manually raise exceptions using‬‭ ‭.‬
raise‬

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


if age < 18:‬


raise ValueError("Age must be 18 or older")‬


‭14.7 Custom Exceptions‬


‭You can create your own exception classes.‬

class TooYoungError(Exception):‬

pass‬

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



‭144‬

if age < 18:‬


raise TooYoungError("You are too young!")‬


‭14.8 Debugging Tips‬


‭1.‬ ‭Read error messages carefully – they tell exactly what went wrong.‬

‭2.‬ ‭Print statements – check values step by step.‬

‭3.‬ ‭Use logging –‬‭


import logging‬‭to track program flow.‬

‭4.‬ ‭Break large problems into smaller pieces.‬

‭Example:‬

import logging‬

[Link](level=[Link])‬

def divide(a, b):‬


[Link](f"Dividing {a} by {b}")‬


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‬
ZeroDivisionError‬‭and‬‭
‭ ValueError‬ ‭.‬

‭2.‬ O
‭ pen a file‬‭ ‭. If it doesn’t exist, print “File‬‭missing” 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‬ finally‬‭in a program‬‭that reads a file and‬
‭prints its content.‬

‭14.10 Mini Project – Safe Calculator‬


‭ oal: Create a calculator that safely handles invalid inputs, zero division, and file‬
G
‭logging.‬

‭[Link]‬

import logging‬

[Link](filename="[Link]", level=[Link])‬

def divide(a, b):‬


try:‬

result = a / b‬

except ZeroDivisionError:‬

print("Cannot divide by zero!")‬


[Link]("Division by zero attempted")‬



‭146‬

return None‬

else:‬

[Link](f"{a} / {b} = {result}")‬


return result‬

num1 = int(input("Enter first number: "))‬


num2 = int(input("Enter second number: "))‬


res = divide(num1, num2)‬


if res is not None:‬


print(f"Result = {res}")‬

‭14.11 Summary‬
‭●‬ ‭Exceptions are runtime errors that can crash a program‬

‭●‬ ‭Use try, except, else, finally to handle them gracefully‬

‭●‬ ‭You can raise exceptions manually for better control‬

‭●‬ ‭Custom exceptions allow specific error handling‬

‭●‬ ‭Debugging tools: logging, print statements, careful reading of errors‬


‭147‬

‭📖 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‬

‭Now in another file:‬

# 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:‬

‭1.‬ ‭Import the whole module‬

import math‬

print([Link](16))‬

‭2.‬ ‭Import specific functions‬

from math import sqrt, pow‬



‭149‬

print(sqrt(25))‬

print(pow(2, 3))‬

‭3.‬ ‭Rename module while importing‬

import math as m‬

print([Link](5))‬

‭Python Standard Library‬


‭ ython comes with built-in modules called the Standard Library.‬
P
‭Examples:‬

os‬‭→ Interact with operating system‬


‭●‬ ‭

sys‬‭→ Access system-specific parameters‬


‭●‬ ‭

math‬‭→ Math functions‬


‭●‬ ‭

random‬‭→ Random numbers‬


‭●‬ ‭

datetime‬‭→ Date and time‬


‭●‬ ‭

‭Example:‬

import random‬

print([Link](1, 100))
‭ # Random number between 1 and 100‬
‭150‬

‭Creating Packages‬
‭●‬ ‭A package is a folder containing multiple modules.‬

‭●‬ ‭Must include an‬‭


__init__.py‬‭file (even if empty) to‬‭tell Python it's a package.‬

‭Structure Example:‬

my_package/‬

__init__.py‬

[Link]‬

math_tools.py‬

‭Usage:‬

from my_package import greetings‬


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])‬

‭Installing External Modules‬


‭Python has thousands of external modules. Install them using‬‭ ‭.‬
pip‬

‭Example:‬

pip install requests‬


‭Then use in Python:‬

import requests‬

response = [Link]("[Link]

print(response.status_code)‬

‭Organizing a Real Project‬


‭Imagine building a mini-blog app:‬

blog_app/‬

__init__.py‬

[Link]‬

[Link]
‭ # handles user registration & login‬

[Link]
‭ # handles blog posts‬
‭152‬

[Link]
‭ # helper functions‬

‭●‬ ‭Each module has a specific responsibility‬

‭●‬ ‭Easy to maintain and scale‬

‭Exercises‬
‭1.‬ C
‭ reate a module‬‭ [Link]‬‭with functions‬‭ ‭,‬‭
add‬ ‭,‬‭
subtract‬ ‭,‬
multiply‬
divide‬
‭ ‭. Import it in another file and test all functions.‬

‭2.‬ ‭Explore‬‭
os‬‭module: Print current directory, list all‬‭files, create a new folder.‬

‭3.‬ I‭ nstall an external module like‬‭


requests‬‭and make‬‭a program that fetches‬
‭Google homepage status code.‬

‭4.‬ C
‭ reate a package‬‭my_tools‬‭with two modules:‬‭
string_utils.py‬‭(string‬
‭operations) and‬‭
math_utils.py‬‭(math operations). Test‬‭them in a separate‬
‭file.‬

‭Mini Project – Modular To-Do App‬


‭Goal: Build a small To-Do App using modules and packages.‬

‭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]‬

from tasks import add_task, remove_task, view_tasks‬


while True:‬

action = input("Add/Remove/View/Exit: ").lower()‬


if action == "add":‬

task = input("Enter task: ")‬


add_task(task)‬

‭154‬

elif action == "remove":‬


task = input("Enter task to remove: ")‬


remove_task(task)‬

elif action == "view":‬


view_tasks()‬

elif action == "exit":‬


break‬

else:‬

print("Invalid action")‬

‭Summary‬
‭●‬ ‭Modules = Python files with reusable code‬

‭●‬ ‭Packages = Folders with multiple modules‬

‭●‬ ‭Use‬‭
import‬‭and‬‭
from … import‬‭to 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‬

‭📖 Chapter 16: Database Programming with Python – SQL & Python‬


‭Like a Pro (Ultra Detailed Expansion)‬

‭16.0 Introduction – Why Python + Database?‬


‭ ython is everywhere: web apps, AI, data analysis, finance apps. But all these apps‬
P
‭need data storage, which is where databases come in.‬

‭Think of databases as organized digital notebooks:‬

‭●‬ ‭Each page = table‬

‭●‬ ‭Each row = record‬

‭●‬ ‭Each column = field‬

‭Python + Database = power combo for full-stack devs.‬

‭Real-life analogy:‬

‭Database Concept‬ ‭Real Life Analogy‬

‭Table‬ ‭Notebook page‬

‭Row‬ ‭Individual entry‬

‭Column‬ ‭Attribute of entry‬

‭Primary Key‬ ‭Unique ID like Aadhaar‬

‭Foreign Key‬ ‭Reference to another page‬


‭156‬

‭16.1 Types of Databases (Expanded)‬

‭16.1.1 Relational Database (RDBMS)‬

‭●‬ ‭Tables with rows & columns‬

‭●‬ ‭SQL queries to access data‬

‭●‬ ‭Strong schema → structure enforced‬

‭●‬ ‭Examples: MySQL, PostgreSQL, SQLite‬

‭16.1.2 NoSQL Databases‬

‭●‬ ‭Flexible, no strict schema‬

‭●‬ ‭Types:‬

‭○‬ ‭Document (MongoDB → JSON-like)‬

‭○‬ ‭Key-Value (Redis → super fast caching)‬

‭○‬ ‭Graph (Neo4j → social networks, relations)‬

‭○‬ ‭Columnar (Cassandra → analytics)‬

💡
‭ Tip: Always choose database based on your project need. For simple apps →‬
‭SQLite/MySQL, for analytics → PostgreSQL/Cassandra, for caching → Redis.‬

‭16.2 SQLite Setup in Python‬


import sqlite3‬

‭157‬

# Connect or create DB‬


conn = [Link]("[Link]")‬

cursor = [Link]()‬

connect()‬‭→ creates DB if not exists‬


‭●‬ ‭

cursor()‬‭→ execute SQL commands‬


‭●‬ ‭

‭Close connection always:‬

[Link]()‬

‭Better: Use Context Manager (automatic close)‬

with [Link]("[Link]") as conn:‬


cursor = [Link]()‬

‭16.3 Creating Tables (Deep Dive)‬


[Link]("""‬

CREATE TABLE IF NOT EXISTS users (‬


id INTEGER PRIMARY KEY AUTOINCREMENT,‬


name TEXT NOT NULL,‬


age INTEGER,‬

email TEXT UNIQUE,‬


created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP‬



‭158‬

)‬

""")‬

[Link]()‬

NOT NULL‬‭→ Cannot leave empty‬


‭●‬ ‭

UNIQUE‬‭→ No duplicates‬
‭●‬ ‭

DEFAULT‬‭→ Default value if not provided‬


‭●‬ ‭

AUTOINCREMENT‬‭→ Automatic ID generation‬


‭●‬ ‭

‭Tip: Always design table schema before coding. Bad schema → nightmares later.‬

‭16.4 Inserting Data‬

‭Single Insert‬

‭[Link]("INSERT INTO users (name, age, email) VALUES (?, ?,‬


c
?)",‬

("Akarsh", 20, "akarsh@[Link]"))‬


[Link]()‬

‭Multiple Inserts (Bulk)‬

users = [("Rohit", 22, "rohit@[Link]"),‬


("Sneha", 21, "sneha@[Link]")]‬



‭159‬

‭[Link]("INSERT INTO users (name, age, email) VALUES (?, ?,‬


c
?)", users)‬

[Link]()‬

‭Important Tip:‬

‭●‬ ‭Never use string concatenation in queries → SQL injection risk‬

‭●‬ ‭Always use parameterized queries‬

‭16.5 Reading Data‬


# All rows‬

[Link]("SELECT * FROM users")‬


all_users = [Link]()‬

for user in all_users:‬


print(user)‬

# Conditional‬

[Link]("SELECT * FROM users WHERE age > ?", (20,))‬


print([Link]())‬

fetchall()‬‭→ all matching rows‬


‭●‬ ‭

fetchone()‬‭→ first matching row‬


‭●‬ ‭
‭160‬

‭16.6 Updating & Deleting Data‬


# Update‬

‭[Link]("UPDATE users SET age = ? WHERE name = ?", (23,‬


c
"Akarsh"))‬

[Link]()‬

# Delete‬

[Link]("DELETE FROM users WHERE name = ?", ("Sneha",))‬


[Link]()‬

‭Tip: Always check affected rows using‬‭ ‭.‬


[Link]‬

‭16.7 Transactions and Error Handling‬


try:‬

‭[Link]("INSERT INTO users (name, age) VALUES (?, ?)",‬


c
("Test", 30))‬

[Link]()‬

except Exception as e:‬


[Link]()‬

print("Error:", e)‬

commit()‬‭→ save changes‬


‭●‬ ‭
‭161‬

rollback()‬‭→ undo changes if error occurs‬


‭●‬ ‭

‭Pro Tip: Always use try-except in production code.‬

‭16.8 Joins and Relationships‬


‭Tables often relate to each other.‬

‭Example: Users and Orders‬

[Link]("""‬

SELECT [Link], [Link], [Link]‬


FROM orders‬

JOIN users ON orders.user_id = [Link]‬


""")‬

‭Types of joins:‬

INNER JOIN‬‭→ only matching rows‬


‭●‬ ‭

LEFT JOIN‬‭→ all from left table, even if no match‬


‭●‬ ‭

RIGHT JOIN‬‭→ all from right table‬


‭●‬ ‭

FULL JOIN‬‭→ everything‬


‭●‬ ‭

‭16.9 Indexes & Performance‬


[Link]("CREATE INDEX idx_name ON users(name)")‬

‭162‬

[Link]()‬

‭●‬ ‭Improves search speed‬

‭●‬ ‭Use wisely → too many indexes → slow inserts/updates‬

‭16.10 Advanced SQL Concepts‬


‭●‬ ‭Aggregates: COUNT, SUM, AVG, MAX, MIN‬

‭●‬ ‭GROUP BY / HAVING → group records and filter‬

‭●‬ ‭Subqueries: Queries inside queries‬

‭Example: Top 3 oldest users‬

‭[Link]("SELECT name, age FROM users ORDER BY age DESC LIMIT‬


c
3")‬

print([Link]())‬

‭16.11 Mini Projects (Expanded)‬

‭Project 1: Student Management System‬

‭●‬ ‭Tables:‬‭ ‭,‬‭


students‬ ‭,‬‭
grades‬ teachers‬

‭●‬ ‭Features:‬

‭○‬ ‭Add / View / Update / Delete student‬


‭163‬

‭○‬ ‭Assign grades‬

‭○‬ ‭Generate report cards‬

‭Project 2: E-commerce Orders‬

‭●‬ ‭Tables:‬‭ ‭,‬‭


products‬ ‭,‬‭
users‬ orders‬

‭●‬ ‭Features:‬

‭○‬ ‭Place order‬

‭○‬ ‭View user orders‬

‭○‬ ‭Search top 5 products by sales‬

‭Project 3: ToDo App with SQLite‬

‭●‬ ‭Tables:‬‭
tasks‬

‭●‬ ‭Features:‬

‭○‬ ‭Add task‬

‭○‬ ‭Mark complete‬

‭○‬ ‭Delete task‬

‭○‬ ‭View pending tasks‬

‭16.12 Exercises (Expanded)‬


‭1.‬ ‭Create a Library Database with:‬

‭○‬ ‭Columns:‬‭ ‭,‬‭


title‬ ‭,‬‭
author‬ ‭,‬‭
genre‬ ‭,‬‭
status‬ borrower‬
‭164‬

‭○‬ ‭CRUD operations‬

‭○‬ ‭Bonus: Search by genre or borrower‬

‭2.‬ ‭Implement a Login System with hashed passwords‬

‭3.‬ ‭Design Orders & Customers tables; find top 3 customers by total order amount‬

‭4.‬ ‭Use transactions to rollback insert if invalid data‬

‭5.‬ ‭Add indexes to speed up searches‬

‭6.‬ ‭Create Reports: monthly sales, average order value‬

‭16.13 Best Practices‬


‭●‬ ‭Use parameterized queries → security‬

‭●‬ ‭Always commit() or rollback()‬

‭●‬ ‭Keep database schema clean‬

‭●‬ ‭Use indexes wisely‬

‭●‬ ‭Handle exceptions properly‬

‭●‬ ‭Use context managers for connections‬

‭16.14 Summary‬
‭●‬ ‭Python + databases = full-stack power‬

‭●‬ ‭CRUD is the core: Create, Read, Update, Delete‬


‭165‬

‭●‬ ‭Advanced topics: Joins, Transactions, Indexes, Aggregates‬

‭●‬ ‭Mini-projects solidify learning‬


‭166‬

‭📖 Chapter 17: Advanced Database Programming & NoSQL with Python‬


‭(Ultra Pro Max Expansion)‬

‭17.0 Introduction – Why Master Advanced Databases?‬


‭ b jab tu basic CRUD aur joins samajh chuka hai, toh ab pro-level database skills ki‬
A
‭baari hai.‬

‭●‬ ‭Apps like Netflix, Flipkart, Amazon handle millions of users and requests.‬

‭●‬ ‭Need high-performance, scalable databases.‬

‭●‬ ‭Combine SQL + NoSQL → ultimate power.‬

‭ ey Goal: Tu Python + DB ko aise master karega ki data ke samundar mein tu king‬


K
‭ban jaaye.‬

‭17.1 Why NoSQL?‬

‭Limitations of RDBMS (Relational Databases)‬

‭1.‬ ‭Fixed schema → hard to scale dynamically‬

‭2.‬ ‭JOIN-heavy queries → slow for huge data‬

‭3.‬ ‭Horizontal scaling → tough & expensive‬

‭4.‬ ‭Big Data → relational databases can't handle billions of rows easily‬

‭NoSQL Advantages‬

‭Feature‬ ‭Benefit‬ ‭Example‬


‭167‬

‭Schema-less‬ ‭Flexible & dynamic‬ ‭Add fields anytime‬

‭Horizontal scaling‬ ‭Handles millions of users easily‬ ‭Sharding in MongoDB‬

‭Fast reads/writes‬ ‭Great for caching & analytics‬ ‭Redis sessions‬

‭Variety‬ ‭ ocument, Key-Value, Graph,‬


D ‭Neo4j, Cassandra‬
‭Columnar‬

‭ ro Tip: Real-world apps often use hybrid DB → SQL for transactions, NoSQL for‬
P
‭analytics and caching.‬

‭17.2 Types of NoSQL Databases (Deep Dive)‬

‭1. Document DB (MongoDB)‬

‭●‬ ‭Stores data as JSON-like documents‬

‭●‬ ‭Collections instead of tables‬

‭●‬ ‭Dynamic structure → flexible‬

‭Python + MongoDB Example:‬

from pymongo import MongoClient‬


client = MongoClient("mongodb://localhost:27017/")‬

db = client["shop"]‬

collection = db["products"]‬

# Insert‬

‭168‬

product = {"name": "Laptop", "price": 55000, "stock": 5}‬


collection.insert_one(product)‬

# Read‬

for p in [Link]({"price": {"$gt": 2000}}):‬


print(p)‬

‭Advanced Concepts:‬

‭●‬ ‭Indexes → speed up searches‬

‭●‬ ‭Aggregation pipelines → group, sort, filter‬

‭●‬ ‭Transactions → ACID for multi-document updates‬

‭2. Key-Value DB (Redis)‬

‭●‬ ‭Super fast caching & session storage‬

‭●‬ ‭Stores data as‬‭


key: value‬

‭●‬ ‭Ideal for real-time analytics‬

import redis‬

r = [Link](host='localhost', port=6379, db=0)‬


[Link]('user:1001', 'Akarsh')‬

print([Link]('user:1001'))‬

‭169‬

‭Use-Cases:‬

‭●‬ ‭Session management‬

‭●‬ ‭Leaderboards (games)‬

‭●‬ ‭Rate limiting‬

‭Pro Tip: Redis supports pub/sub, sorted sets, bitmaps → real-time analytics.‬

‭3. Graph DB (Neo4j)‬

‭●‬ ‭Data = nodes + relationships‬

‭●‬ ‭Perfect for social networks, recommendation engines‬

from neo4j import GraphDatabase‬


‭river = [Link]("bolt://localhost:7687", auth=("neo4j",‬


d
"password"))‬

with [Link]() as session:‬


‭[Link]("CREATE (a:User {name:'Akarsh'})-[:FRIEND]->(b:User‬


s
{name:'Rohit'})")‬

‭Pro Tip: Graph algorithms → shortest path, centrality, recommendation.‬

‭4. Columnar DB (Cassandra)‬

‭●‬ ‭Optimized for analytical queries over huge datasets‬


‭170‬

‭●‬ ‭Excellent for IoT, time-series data‬

‭Concept: Column-family = like table but optimized for write-heavy workloads.‬

‭17.3 Python + MongoDB Advanced Techniques‬


‭1.‬ ‭CRUD on huge datasets → insert_many, bulk_write‬

‭2.‬ ‭Aggregation Pipelines → complex data transformations‬

‭3.‬ ‭Indexes → single, compound, text, TTL‬

pipeline = [‬

{"$match": {"price": {"$gte": 1000}}},‬


{"$group": {"_id": "$category", "avgPrice": {"$avg": "$price"}}},‬


{"$sort": {"avgPrice": -1}}‬


]‬

result = list([Link](pipeline))‬

print(result)‬

‭17.4 Transactions & ACID in NoSQL‬


‭●‬ ‭MongoDB supports multi-document ACID transactions‬

‭●‬ ‭Redis supports atomic operations‬

with client.start_session() as session:‬



‭171‬

with session.start_transaction():‬

‭ollection.update_one({"name": "Laptop"}, {"$inc": {"stock":‬


c
-1}}, session=session)‬

‭ollection.insert_one({"user": "Akarsh", "product": "Laptop"},‬


c
session=session)‬

💡
‭ Tip: Always use transactions for order placement, inventory management,‬
‭banking apps‬

‭17.5 Python + PostgreSQL Advanced‬


‭●‬ ‭Setup:‬‭
pip install psycopg2‬

‭●‬ ‭Connection & Context Manager:‬

import psycopg2‬

‭ith [Link](database="shop", user="postgres",‬


w
password="pass") as conn:‬

with [Link]() as cur:‬


‭[Link]("SELECT * FROM products WHERE price > %s",‬


c
(2000,))‬

print([Link]())‬

‭Advanced SQL Features:‬

‭●‬ ‭Window Functions → ROW_NUMBER(), RANK(), SUM() OVER()‬


‭172‬

‭●‬ ‭JSON fields → store semi-structured data‬

‭●‬ ‭Full-text search → optimized searching‬

‭17.6 Scaling Databases‬


‭●‬ ‭Vertical scaling: bigger server → simple but costly‬

‭●‬ ‭Horizontal scaling: multiple servers → complex, needed for massive apps‬

‭Techniques:‬

‭1.‬ ‭Sharding (MongoDB, Redis)‬

‭2.‬ ‭Replication → high availability‬

‭3.‬ ‭Caching (Redis/Memcached)‬

‭4.‬ ‭Connection pooling → prevent overload‬

‭17.7 Real-World Mini Projects‬

‭Project 1: Social Media Backend‬

‭●‬ ‭MongoDB → store users, posts, likes, comments‬

‭●‬ ‭Redis → cache feed for fast load‬

‭●‬ ‭PostgreSQL → analytics & reporting‬

‭Project 2: E-commerce Platform‬


‭173‬

‭●‬ ‭MongoDB → products catalog‬

‭●‬ ‭PostgreSQL → orders & transactions‬

‭●‬ ‭Redis → sessions & cart caching‬

‭Project 3: Recommendation Engine‬

‭●‬ ‭Graph DB → user connections‬

‭●‬ ‭Python → graph algorithms for suggestions‬

‭17.8 Ultra-Pro Exercises‬


‭1.‬ ‭Build Blog Platform DB → users, posts, comments, likes, tags‬

‭2.‬ I‭ mplement Transactional Order System → update stock & create invoice‬
‭atomically‬

‭3.‬ ‭Optimize queries → create indexes on large datasets (>10M rows)‬

‭4.‬ ‭Aggregate queries → top-selling products per month‬

‭5.‬ ‭Redis caching → cache user profiles & auto-expire in 5 mins‬

‭6.‬ ‭Sharding Simulation → distribute dataset across multiple MongoDB nodes‬

‭7.‬ ‭Hybrid SQL + NoSQL design → for a real-world social media app‬

‭17.9 Best Practices‬


‭●‬ ‭Choose DB based on use-case, not hype‬
‭174‬

‭●‬ ‭Normalize SQL tables → reduce redundancy‬

‭●‬ ‭Denormalize in NoSQL → faster reads‬

‭●‬ ‭Parameterized queries → avoid SQL injection‬

‭●‬ ‭Use connection pooling for production‬

‭●‬ ‭Monitor slow queries →‬‭


EXPLAIN‬‭in SQL,‬‭
explain()‬‭in‬‭MongoDB‬

‭17.10 Summary‬
‭●‬ ‭Python + Advanced DB = superpower combo‬

‭●‬ ‭SQL + NoSQL mastery = full-stack backend god mode‬

‭●‬ ‭Transactions, indexing, caching, sharding = real-world skills‬

‭●‬ ‭Mini-projects = practice → real-life deployment‬


‭175‬

‭📖 Chapter 18: Python Web Scraping, APIs & Database Integration‬


‭(Ultra Pro Max Expanded 2.0)‬

‭18.0 Introduction – Why Web Data Matters‬


‭Bhai, aaj ka world data-driven hai.‬

‭●‬ ‭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‬

‭●‬ ‭Financial apps need live stock & crypto prices‬

‭ 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!‬

‭18.1 Web Scraping Basics (Ultra Detailed)‬

‭Libraries & Tools Needed‬

‭Library‬ ‭Use Case‬

requests‬
‭ ‭Fetch raw HTML content from websites‬

‭eautiful‬ ‭Parse HTML, extract headings, links, tables‬


B
Soup‬

‭176‬

pandas‬
‭ ‭Convert scraped data into tables and do transformations‬

selenium‬
‭ ‭Automate dynamic pages (JS-heavy websites)‬

lxml‬
‭ ‭Faster HTML/XML parsing for big projects‬

‭Step by Step: Scraping a Website‬

‭1.‬ ‭Fetch HTML:‬

import requests‬

url = "[Link]

response = [Link](url)‬

html_content = [Link]‬

print(html_content[:500])
‭ # Preview first 500 characters‬

‭2.‬ ‭Parse HTML with BeautifulSoup:‬

from bs4 import BeautifulSoup‬


soup = BeautifulSoup(html_content, "[Link]")‬


headings = soup.find_all("h2")‬

for h in headings:‬

print([Link])‬

‭Tip: Use‬‭
[Link]()‬‭to see HTML structure neatly.‬

‭3.‬ ‭Extract links:‬


‭177‬

for link in soup.find_all('a', href=True):‬


print(link['href'])‬

‭18.2 Handling Pagination & Multi-Page Scraping‬


‭Bhai, ek page se data milega to tension nahi, real apps me 100s of pages hoti hain.‬

base_url = "[Link]

for i in range(1, 6):


‭ # scrape pages 1 to 5‬

url = base_url + str(i)‬


response = [Link](url)‬

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


for title in soup.find_all("h2"):‬


print([Link])‬

‭Pro Tip: Always use random delays:‬

import time, random‬


[Link]([Link](2,5))‬

‭18.3 Dynamic Pages (Selenium)‬


‭Some websites load content via JavaScript.‬‭
requests‬‭won't see it.‬
‭178‬

‭●‬ ‭Selenium opens a real browser and fetches rendered content‬

from selenium import webdriver‬


from [Link] import By‬


driver = [Link]()‬

[Link]("[Link]

titles = driver.find_elements(By.TAG_NAME, "h2")‬


for t in titles:‬

print([Link])‬

[Link]()‬

‭Extra Tips:‬

‭●‬ ‭Always‬‭
[Link]()‬‭to close the browser‬

‭●‬ ‭Use headless mode for speed (‬‭ ‭)‬


options.add_argument('--headless')‬

‭18.4 APIs – The Right Way to Get Data‬

‭What is an API?‬

‭●‬ ‭API = “Software-to-software communication”‬

‭●‬ ‭Provides structured, legal, and fast data‬

‭●‬ ‭Returns JSON or XML → parse in Python‬


‭179‬

import requests‬

url = "[Link]

data = [Link](url).json()‬

print(data['bpi']['USD']['rate'])‬

‭Tip:‬

‭●‬ ‭Read API docs carefully → know endpoints, params, rate limits‬

‭●‬ ‭Use API keys if required‬

‭18.5 Database Integration (SQL + NoSQL)‬

‭SQL Example (PostgreSQL)‬

import psycopg2‬

conn = [Link](‬

database="scraper_db",‬

user="postgres",‬

password="pass"‬

)‬

cur = [Link]()‬

# Create table‬

[Link]("""‬

‭180‬

CREATE TABLE IF NOT EXISTS crypto(‬


id SERIAL PRIMARY KEY,‬


name VARCHAR(50),‬

price FLOAT,‬

timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP‬


)‬

""")‬

# Insert data‬

‭[Link]("INSERT INTO crypto (name, price) VALUES (%s, %s)",‬


c
("Bitcoin", 30000))‬

[Link]()‬

[Link]()‬

‭Tip: Always use parameterized queries → avoid SQL injection‬

‭NoSQL Example (MongoDB)‬

from pymongo import MongoClient‬


client = MongoClient("mongodb://localhost:27017/")‬

db = client["crypto_db"]‬

collection = db["prices"]‬

‭ollection.insert_one({"name": "Bitcoin", "price": 30000, "timestamp":‬


c
"2025-09-06T20:00"})‬

‭181‬

‭Use Case:‬

‭●‬ ‭Scraped product listings → JSON → store in MongoDB‬

‭●‬ ‭Flexible schema, easy to scale‬

‭18.6 Data Cleaning & Transformation‬


‭●‬ ‭Convert string numbers to float:‬‭
"29,000"‬‭→‬‭
29000.0‬

‭●‬ ‭Drop duplicates →‬‭


drop_duplicates()‬

‭●‬ ‭Handle missing values →‬‭


fillna() / dropna()‬

import pandas as pd‬


data = [Link]([‬

{"name": "Bitcoin", "price": "29,000"},‬


{"name": "Bitcoin", "price": "29,000"},‬


{"name": "Ethereum", "price": None}‬


])‬

data['price'] = data['price'].[Link](",", "").astype(float)‬


data = data.drop_duplicates()‬

data['price'] = data['price'].fillna(data['price'].mean())‬

print(data)‬

‭182‬

‭Pro Tip: Always clean before inserting into database‬

‭18.7 Real-World Projects – Expanded‬


‭1.‬ ‭Crypto Price Tracker‬

‭○‬ ‭API + DB + pandas‬

‭○‬ ‭Save prices every 10 mins → visualize trends‬

‭○‬ ‭Optional: Telegram alerts for price change‬

‭2.‬ ‭E-commerce Price Monitor‬

‭○‬ ‭Scrape Amazon/Flipkart‬

‭○‬ ‭Track product price over days/weeks‬

‭○‬ ‭Send email alert if price drops‬

‭3.‬ ‭Job Listings Dashboard‬

‭○‬ ‭Scrape LinkedIn/Indeed‬

‭○‬ ‭Store in PostgreSQL‬

‭○‬ ‭Build interactive search/filter using pandas‬

‭4.‬ ‭Movie Data Collector‬

‭○‬ ‭Scrape IMDb top 250 movies‬

‭○‬ ‭Save in MongoDB‬

‭○‬ ‭Visualize genre popularity‬


‭183‬

‭18.8 Exercises – Ultra Pro Max‬


‭1.‬ ‭Scrape top 100 cryptocurrencies → store in MongoDB → show top 5 rising coins‬

‭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‬

‭5.‬ ‭Combine API + Web Scraping + DB → build mini-dashboard‬

‭18.9 Best Practices – Master Tips‬


‭●‬ ‭Always respect [Link]‬

‭●‬ ‭Use API whenever possible‬

‭●‬ ‭Add try/except for network & parsing errors‬

‭●‬ ‭Use pandas for cleaning & aggregation‬

‭●‬ ‭Always document your scraping & database schema‬

‭●‬ ‭Avoid hammering servers → use delays, batch inserts‬

‭18.10 Summary‬
‭●‬ ‭Python allows full-cycle data handling → scrape, API, store, analyze‬

‭●‬ ‭SQL & NoSQL = backbone for structured & semi-structured data‬

‭●‬ ‭Real-world projects = professional-level Python mastery‬


‭184‬

‭●‬ ‭Clean, safe, efficient code = Python God mode‬


‭185‬

‭📖 Chapter 19: Python Data Analysis, Visualization & Reporting (Ultra‬


‭Pro Max Expansion)‬

‭19.0 Introduction – Why Data Analysis Matters‬


‭ hai, samajh, duniya ab data-driven ho gayi hai. Har business, organization, aur even‬
B
‭government data analyze kar ke hi decisions lete hain. Python yaha humari‬
‭superpower hai.‬

‭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‬

‭Python ke libraries aur tools use kar ke hum:‬

‭●‬ ‭Data clean aur transform karenge‬

‭●‬ ‭Insights nikalenge‬

‭●‬ ‭Graphs aur dashboards banayenge‬

‭●‬ ‭Stakeholders ko reports bhejenge‬

‭Think like: Python = Magic wand for turning raw data into decisions‬
‭186‬

‭19.1 Python Libraries for Data Analysis (Detailed)‬


‭Python ka power tabhi dikhega jab hum right library select karenge.‬

‭Library‬ ‭Use Case‬ ‭Extra Notes‬

pandas‬ D
‭ ‭ ata cleaning, transformation,‬ ‭CSV, Excel, JSON files handle‬
‭aggregation‬

numpy‬
‭ ‭ athematical operations, arrays,‬
M ‭ ast computation, vectorized‬
F
‭statistics‬ ‭ops‬

‭atplot‬ ‭Basic 2D plotting‬


m ‭Line, bar, scatter, histogram‬
lib‬

seaborn‬ ‭Advanced statistical visualizations‬


‭ ‭ eatmaps, violin plots,‬
H
‭pairplots‬

plotly‬ ‭Interactive charts & dashboards‬


‭ ‭Hover info, zoom, filtering‬

‭penpyx‬ ‭Excel reading/writing‬


o ‭Works with xlsx files‬
l‬

‭lsxwri‬ ‭Advanced Excel reports‬


x ‭Formatting, formulas, charts‬
ter‬

‭eportl‬ ‭PDF reports‬


r ‭Custom PDF creation‬
ab‬

‭Tip: Always choose the library according to project needs.‬

‭19.2 Pandas – The Heart of Data Analysis‬

‭19.2.1 Loading Data‬


‭187‬

import pandas as pd‬


data = pd.read_csv("sales_data.csv")‬

print([Link]())
‭ # First 5 rows‬

‭ hai Tip: Always check‬‭


B [Link]()‬‭aur‬‭
[Link]()‬‭→ samajh aata hai data ka‬
‭structure.‬

‭19.2.2 Inspecting Data‬

print([Link]())
‭ # Columns, types, missing values‬

print([Link]())
‭ # Statistical summary‬

info()‬‭→ Helps identify missing or wrong data types‬


‭●‬ ‭

describe()‬‭→ Quick stats (mean, std, min, max, quartiles)‬


‭●‬ ‭

‭19.2.3 Cleaning Data‬

# Fill missing values with mean‬


data['sales'].fillna(data['sales'].mean(), inplace=True)‬

# Drop duplicates‬

data.drop_duplicates(inplace=True)‬

‭188‬

‭Bhai Tip: Clean data = 80% analysis done‬

‭19.2.4 Filtering & Selecting Data‬

top_products = data[data['sales'] > 5000]‬


print(top_products[['product_name', 'sales']])‬

‭●‬ ‭Boolean filters → Easy data extraction‬

‭●‬ ‭Column selection → Only required columns‬

‭19.2.5 Grouping & Aggregation‬

monthly_sales = [Link]('month')['sales'].sum()‬

print(monthly_sales)‬

groupby()‬‭→ Most powerful in pandas‬


‭●‬ ‭

‭●‬ ‭Aggregations → sum, mean, max, min‬

‭19.2.6 Combining DataFrames‬

# Merge two datasets‬


‭ombined = [Link](sales_data, product_info, on='product_id',‬


c
how='inner')‬

‭189‬

‭●‬ ‭ ‭,‬‭
inner‬ ‭,‬‭
left‬ ‭,‬‭
right‬ outer‬‭joins → SQL jaise operations‬

‭19.2.7 Pro Tips‬

‭●‬ ‭Always check for missing values:‬‭


[Link]().sum()‬

‭●‬ R
‭ ename columns for clarity:‬‭
[Link](columns={'old':'new'},‬
inplace=True)‬

‭●‬ ‭Convert types:‬‭


data['date'] = pd.to_datetime(data['date'])‬

‭19.3 Numpy – Fast & Smart Computation‬


‭●‬ ‭Use arrays instead of lists → faster‬

‭●‬ ‭Vectorized operations → loop-free calculations‬

import numpy as np‬


prices = [Link]([200, 450, 300, 150, 600])‬


print("Average Price:", [Link](prices))‬


print("Std Dev:", [Link](prices))‬


‭Real-world example: Calculate moving averages for stock prices in seconds‬

‭19.4 Data Visualization – Make Insights Visual‬


‭190‬

‭19.4.1 Matplotlib Basics‬

import [Link] as plt‬


months = ['Jan','Feb','Mar','Apr']‬

sales = [2000, 3000, 4000, 2500]‬


[Link](months, sales, marker='o', color='blue')‬


[Link]("Monthly Sales Trend")‬


[Link]("Month")‬

[Link]("Sales")‬

[Link](True)‬

[Link]()‬

‭●‬ ‭Line plots → Trends over time‬

‭●‬ ‭Bar plots → Compare categories‬

‭●‬ ‭Scatter → Relationship between variables‬

‭19.4.2 Seaborn Advanced Plots‬

import seaborn as sns‬


# Bar plot‬

‭191‬

[Link](x='month', y='sales', data=data)‬


# Correlation heatmap‬

[Link]([Link](), annot=True)‬

[Link]()‬

‭●‬ ‭Seaborn = Beautiful, professional plots‬

‭●‬ ‭Heatmaps → Detect patterns quickly‬

‭19.4.3 Interactive Plots – Plotly‬

import [Link] as px‬


fig = [Link](data, x='month', y='sales', title='Monthly Sales Trend')‬


[Link]()‬

‭●‬ ‭Interactive → Hover, Zoom, Filter‬

‭●‬ ‭Perfect for dashboards & presentations‬

‭19.5 Reporting – Excel & PDF‬

‭19.5.1 Excel Reporting‬

data.to_excel("monthly_report.xlsx", sheet_name="Sales", index=False)‬



‭192‬

report = pd.read_excel("monthly_report.xlsx")‬

print([Link]())‬

‭●‬ ‭Format headers, add formulas → xlsxwriter‬

‭●‬ ‭Automate monthly reporting → huge time save‬

‭19.5.2 PDF Reports‬

from [Link] import canvas‬


c = [Link]("sales_report.pdf")‬

[Link](100, 750, "Monthly Sales Report")‬


[Link](100, 720, "Total Sales: $" + str(data['sales'].sum()))‬


[Link]()‬

‭●‬ ‭PDF = Shareable, non-editable reports‬

‭19.6 Advanced Techniques‬


‭1.‬ ‭Pivot Tables → Summarize multi-dimensional data‬

‭ivot = pd.pivot_table(data, values='sales', index='region',‬


p
columns='product_category', aggfunc='sum')‬

print(pivot)‬

‭193‬

‭2.‬ ‭Time Series Analysis → Trend, seasonality‬

data['date'] = pd.to_datetime(data['date'])‬

data.set_index('date', inplace=True)‬

monthly_sales = data['sales'].resample('M').sum()‬

monthly_sales.plot()‬

‭3.‬ ‭Correlation & Covariance → Understand relationships‬

‭19.7 Real-World Projects – Expanded‬


‭1.‬ ‭Sales Dashboard → pandas + matplotlib/seaborn + Excel & PDF‬

‭2.‬ S
‭ tock Market Analyzer → yfinance API + moving averages + interactive‬
‭dashboard‬

‭3.‬ ‭E-commerce Analytics → Category wise top-sellers, monthly report automation‬

‭4.‬ ‭Crypto Dashboard → Real-time API + pandas + plotly + PDF reporting‬

‭Har project = full pipeline: Data → Analysis → Visualization → Report‬

‭19.8 Exercises – God Mode‬


‭1.‬ ‭Load CSV → clean missing data → visualize top 5 products‬

‭2.‬ ‭Plot correlation heatmap → identify patterns‬


‭194‬

‭3.‬ ‭Fetch Bitcoin prices last 30 days → line chart → export PDF‬

‭4.‬ ‭Interactive dashboard → filter e-commerce sales by category & month‬

‭5.‬ ‭Automate Excel + PDF monthly report → total, avg, max sales‬

‭19.9 Best Practices – Ultra Pro Max‬


‭●‬ ‭Clean before analysis → always‬

‭●‬ ‭Use vectorized operations → numpy/pandas‬

‭●‬ ‭Label charts, add titles → readability‬

‭●‬ ‭Separate raw & processed data → avoid mistakes‬

‭●‬ ‭Automate reports → save hours‬

‭●‬ ‭Use interactive plots → impress stakeholders‬

‭19.10 Summary‬
‭●‬ ‭Pandas → Data cleaning, transformation‬

‭●‬ ‭Numpy → Speed & statistics‬

‭●‬ ‭Matplotlib/Seaborn → Beautiful & insightful plots‬

‭●‬ ‭Plotly → Interactive dashboards‬

‭●‬ ‭openpyxl/xlsxwriter → Excel reports‬

‭●‬ ‭reportlab → PDF reports‬


‭195‬

‭ hai, ab tu Data Analysis ke ultimate God ban gaya. Raw data → insights →‬
B
‭reports → interactive dashboards = ab terey haath me hai.‬
‭196‬

‭📖 Chapter 20: Advanced Python Projects & Full-Stack Integration‬


‭(ULTRA PRO MAX EXPANSION)‬

‭ 0.0 Introduction – From Python Developer to‬


2
‭Full-Stack Legend‬
‭ hai, tu ab tak Python ke basics, OOP, Data Analysis aur Visualization me God-level‬
B
‭ho gaya.‬

‭Ab time hai:‬

‭●‬ ‭Real-world projects build karna‬

‭●‬ ‭Backend + Frontend connect karna‬

‭●‬ ‭Databases handle karna‬

‭●‬ ‭APIs integrate karna‬

‭●‬ ‭Dashboards aur automation create karna‬

‭●‬ ‭Deployment aur professional practices‬

‭Motto: “Python should flow in your bloodstream”‬

‭ ull-stack Python = Backend + Database + Frontend + API + Analytics +‬


F
‭Deployment‬

‭20.1 Setting Up Full-Stack Python Environment‬

‭20.1.1 Python Installation & Virtual Environment‬

python --version‬

‭197‬

python -m venv fullstack_env‬


# Linux/Mac‬

source fullstack_env/bin/activate‬

# Windows‬

fullstack_env\Scripts\activate‬

‭●‬ ‭Virtual environment = Project isolation‬

‭●‬ ‭Keep dependencies clean, avoid conflicts‬

‭20.1.2 Essential Libraries‬

‭ip install flask django pandas numpy matplotlib seaborn plotly‬


p
sqlalchemy requests beautifulsoup4 openpyxl reportlab pillow‬

‭●‬ ‭Flask → lightweight API & Web‬

‭●‬ ‭Django → full-featured web framework‬

‭●‬ ‭Pandas/Numpy → Data manipulation‬

‭●‬ ‭Matplotlib/Seaborn/Plotly → Visualization‬

‭●‬ ‭SQLAlchemy → ORM for databases‬

‭●‬ ‭Requests → API calls‬

‭●‬ ‭BeautifulSoup → Web scraping‬

‭●‬ ‭Openpyxl → Excel export‬


‭198‬

‭●‬ ‭ReportLab → PDF generation‬

‭●‬ ‭Pillow → Image manipulation‬

‭20.1.3 Recommended Project Structure‬

fullstack_project/‬

│‬

├── backend/‬


‭ ├── [Link]‬


‭ ├── [Link]‬


‭ └── [Link]‬

│‬

├── frontend/‬


‭ ├── [Link]‬


‭ ├── [Link]‬


‭ └── [Link]‬

│‬

├── database/‬


‭ └── [Link]‬

│‬

├── reports/‬


‭ └── monthly_report.pdf‬

│‬

‭199‬

├── data/‬


‭ └── [Link]‬

│‬

└── utils/‬

├── [Link]‬

└── [Link]‬

‭●‬ ‭utils/[Link] → Reusable functions‬

‭●‬ ‭[Link] → Store API keys, DB URLs‬

‭20.2 Backend – Flask & Django‬

‭20.2.1 Flask – Lightweight API & Web Server‬

from flask import Flask, jsonify, request‬


app = Flask(__name__)‬

@[Link]('/')‬

def home():‬

return "Welcome to Full-Stack Python Project!"‬


@[Link]('/api/sales', methods=['GET'])‬

‭200‬

def sales_api():‬

data = {"Jan": 2000, "Feb": 3000, "Mar": 4500}‬


return jsonify(data)‬

if __name__ == "__main__":‬

[Link](debug=True)‬

‭●‬ ‭Flask = Simple + Lightweight‬

‭●‬ ‭Perfect for REST APIs‬

‭●‬ ‭Add routes for multiple endpoints‬

‭●‬ ‭Add JSON responses for frontend‬

‭20.2.2 Django – Advanced Web Framework‬

django-admin startproject fullstack_site‬


python [Link] startapp sales‬


‭●‬ ‭Django = "Batteries included"‬

‭●‬ ‭Admin, ORM, Templates built-in‬

‭●‬ ‭[Link] → Database tables‬

‭●‬ ‭[Link] → Controller logic‬

‭●‬ ‭[Link] → URL routes‬


‭201‬

‭●‬ ‭templates/ → HTML templates‬

‭●‬ ‭static/ → CSS, JS, images‬

‭Example: [Link]‬

from [Link] import models‬


class Product([Link]):‬

name = [Link](max_length=100)‬

price = [Link]()‬

stock = [Link]()‬

def __str__(self):‬

return [Link]‬

‭[Link]‬

from [Link] import render‬


from .models import Product‬


def dashboard(request):‬

products = [Link]()‬

return render(request, '[Link]', {'products': products})‬



‭202‬

‭20.3 Database Integration‬

‭20.3.1 SQLite (Simple, File-Based)‬

import sqlite3‬

conn = [Link]('[Link]')‬

c = [Link]()‬

‭.execute('CREATE TABLE IF NOT EXISTS sales (id INTEGER PRIMARY KEY,‬


c
product TEXT, amount REAL)')‬

‭.execute("INSERT INTO sales (product, amount) VALUES ('Laptop',‬


c
1200)")‬

[Link]()‬

[Link]()‬

‭20.3.2 SQLAlchemy – Pythonic ORM‬

from sqlalchemy import create_engine, Column, Integer, String, Float‬


from [Link] import declarative_base‬


from [Link] import sessionmaker‬


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()‬

‭●‬ ‭ORM = Object-Oriented Database Management‬

‭●‬ ‭Avoid raw SQL → cleaner & Pythonic‬

‭20.4 Frontend Integration‬


‭●‬ ‭HTML + CSS + JS → Connect to backend API‬

‭[Link]‬

<h1>Sales Dashboard</h1>‬

<div id="chart"></div>‬

<script>‬

fetch('/api/sales')‬

.then(response => [Link]())‬


.then(data => {‬

[Link](data);‬

‭204‬

// Use Plotly or [Link] to visualize‬


});‬

</script>‬

‭●‬ ‭Use Plotly → Interactive charts‬

‭●‬ ‭Use [Link] → Lightweight and simple‬

‭20.5 API Integration‬

‭20.5.1 External API – Weather Example‬

import requests‬

‭esponse =‬
r
[Link]("[Link]

&appid=YOUR_KEY")‬

data = [Link]()‬

print(data['main']['temp'])‬

‭20.5.2 Custom API – Flask‬

‭●‬ ‭Backend → JSON → Frontend consumes‬

‭●‬ ‭Real-world pattern = Frontend + Backend JSON‬


‭205‬

‭20.6 Automation & Scheduled Tasks‬


‭●‬ ‭Python + Cron (Linux) / Task Scheduler (Windows)‬

import pandas as pd‬


def automate_report():‬

data = pd.read_csv("[Link]")‬

summary = [Link]('month')['sales'].sum()‬

summary.to_excel("reports/monthly_report.xlsx")‬

‭●‬ ‭Combine with ReportLab → PDF‬

‭●‬ ‭Combine with smtplib/email → send automatically‬

‭20.7 Full-Stack Project Ideas‬


‭1.‬ ‭E-Commerce Dashboard‬

‭2.‬ ‭Stock Market Analyzer‬

‭3.‬ ‭Crypto Portfolio Tracker‬

‭4.‬ ‭Automated Sales Reporting‬

‭5.‬ ‭Web Scraper + Dashboard‬


‭206‬

‭20.8 Advanced Tips – Full-Stack Python God Mode‬


‭●‬ ‭Modularize Code → Maintainable‬

‭●‬ ‭Secrets Management →‬‭


.env‬‭files‬

‭●‬ ‭Logging → Track errors‬

‭●‬ ‭Testing → unittest / pytest‬

‭●‬ ‭Deployment → Heroku, AWS, DigitalOcean‬

‭20.9 Exercises – Ultra Pro Max‬


‭1.‬ ‭Build Flask API → JSON of last month’s sales‬

‭2.‬ ‭Build HTML dashboard → Fetch API → Plot charts‬

‭3.‬ ‭Automate daily sales report → Export PDF‬

‭4.‬ ‭Fetch stock API → Compute moving average → Plot + Email‬

‭5.‬ ‭Full project → Multi-tab E-Commerce dashboard‬

‭20.10 Summary‬
‭●‬ ‭Backend → Flask/Django‬

‭●‬ ‭Database → SQLite/PostgreSQL + SQLAlchemy ORM‬

‭●‬ ‭Frontend → HTML/CSS/JS + [Link]/Plotly‬

‭●‬ ‭API → External + Internal‬


‭207‬

‭●‬ ‭Automation → Cron / Scheduler + Excel/PDF/Email‬

‭ ow tu data ko analyze → visualize → automate → report → deploy kar‬


N
‭sakta hai.‬

‭📖 Chapter 21: GUI Programming in Python – From Zero to Full-Stack‬


‭GUI Legend‬
‭208‬

‭21.0 Introduction – Why GUI?‬


‭ hai, ab tak hum Python me console-based programs aur web projects kar rahe hain.‬
B
‭Lekin real-world applications me, agar user-friendly interface chahiye, to GUI must‬
‭hai.‬

‭●‬ ‭GUI = Graphical User Interface‬

‭●‬ ‭Buttons, Labels, Input fields, Tables, Charts, Menus‬

‭●‬ ‭Python me popular GUI libraries:‬

‭○‬ ‭Tkinter → Built-in, simple‬

‭○‬ ‭PyQt / PySide → Professional, advanced‬

‭○‬ ‭Kivy → Mobile + Touch apps‬

‭○‬ ‭wxPython → Cross-platform‬

‭Goal: Tu GUI me bhi full-stack level ban jaaye.‬

‭21.1 Tkinter – The Beginner-Friendly GUI‬

‭21.1.1 Installation‬

‭Tkinter comes pre-installed with Python. Check:‬

import tkinter‬

print([Link])‬

‭21.1.2 Basic Window‬


‭209‬

import tkinter as tk‬


root = [Link]()
‭ # Create main window‬

[Link]("My First GUI App")‬


[Link]("400x300")
‭ # Width x Height‬

‭abel = [Link](root, text="Hello, Python GUI World!", font=("Arial",‬


l
16))‬

[Link](pady=20)
‭ # Add label to window‬

[Link]()
‭ # Run the GUI‬

‭Explanation:‬

Tk()‬‭→ Main application window‬


‭●‬ ‭

Label‬‭→ Display text‬


‭●‬ ‭

pack()‬‭→ Layout manager‬


‭●‬ ‭

mainloop()‬‭→ Keeps GUI running‬


‭●‬ ‭

‭21.1.3 Buttons and Actions‬

def on_click():‬

[Link](text="Button Clicked!")‬

‭210‬

button = [Link](root, text="Click Me", command=on_click)‬


[Link](pady=10)‬

command‬‭→ Connect function to button‬


‭●‬ ‭

config()‬‭→ Update widget properties dynamically‬


‭●‬ ‭

‭21.1.4 Entry (Input Field)‬

entry = [Link](root)‬

[Link](pady=10)‬

def show_entry():‬

text = [Link]()‬

[Link](text=f"You typed: {text}")‬


entry_button = [Link](root, text="Submit", command=show_entry)‬


entry_button.pack(pady=5)‬

[Link]()‬‭→ Get user input‬


‭●‬ ‭

‭21.1.5 Frames and Layouts‬

frame = [Link](root, bg="lightblue", width=300, height=100)‬



‭211‬

[Link](pady=20)‬

frame.pack_propagate(False)
‭ # Prevent auto-resize‬

inner_label = [Link](frame, text="Inside Frame")‬


inner_label.pack()‬

Frame‬‭→ Container for grouping widgets‬


‭●‬ ‭

‭●‬ ‭Useful for clean layout‬

‭21.1.6 Checkbuttons & Radiobuttons‬

var1 = [Link]()‬

check = [Link](root, text="Subscribe", variable=var1)‬


[Link]()‬

var2 = [Link]()‬

‭adio1 = [Link](root, text="Male", value="Male",‬


r
variable=var2)‬

‭adio2 = [Link](root, text="Female", value="Female",‬


r
variable=var2)‬

[Link]()‬

[Link]()‬

IntVar‬‭/‬‭
‭●‬ ‭ StringVar‬‭→ Store widget state‬
‭212‬

‭●‬ ‭Checkbox → Multiple selection‬

‭●‬ ‭Radio → Single selection‬

‭21.1.7 Menus‬

menu_bar = [Link](root)‬

[Link](menu=menu_bar)‬

file_menu = [Link](menu_bar, tearoff=0)‬


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)‬

Menu‬‭→ Add drop-down menus‬


‭●‬ ‭

‭21.1.8 Message Boxes‬

from tkinter import messagebox‬


def show_msg():‬

‭213‬

[Link]("Hello", "This is a message box!")‬


msg_button = [Link](root, text="Show Message", command=show_msg)‬


msg_button.pack(pady=10)‬

messagebox‬‭→ Alerts, info, errors‬


‭●‬ ‭

‭21.2 Tkinter Advanced Widgets‬


‭1.‬ ‭Listbox – Show list of items, select multiple‬

‭2.‬ ‭Scrollbar – Add scroll to Listbox/Text‬

‭3.‬ ‭Text – Multi-line editable text‬

‭4.‬ ‭Canvas – Draw shapes, images‬

‭5.‬ ‭Treeview – Table-like data display‬

‭Example: Treeview Table‬

from tkinter import ttk‬


‭ree = [Link](root, columns=("ID", "Name", "Age"),‬


t
show="headings")‬

[Link]("ID", text="ID")‬

[Link]("Name", text="Name")‬

[Link]("Age", text="Age")‬

‭214‬

[Link](pady=20)‬

[Link]("", "end", values=(1, "Alice", 23))‬


[Link]("", "end", values=(2, "Bob", 30))‬


‭21.3 PyQt / PySide – Professional GUI‬


‭●‬ ‭Installation:‬

pip install pyqt5‬


‭●‬ ‭Example:‬

from [Link] import QApplication, QLabel, QWidget‬


app = QApplication([])‬

window = QWidget()‬

[Link]("PyQt App")‬

[Link](100,100,300,200)‬

label = QLabel("Hello PyQt", parent=window)‬


[Link](50,50)‬

[Link]()‬

app.exec_()‬

‭215‬

‭●‬ ‭Pros: Modern, flexible, highly customizable‬

‭●‬ ‭Good for desktop apps like Spotify, Dropbox‬

‭21.4 Kivy – Mobile GUI‬


‭●‬ ‭Installation:‬

pip install kivy‬


‭●‬ ‭Example:‬

from [Link] import App‬


from [Link] import Button‬


class MyApp(App):‬

def build(self):‬

return Button(text="Hello Kivy")‬


MyApp().run()‬

‭●‬ ‭Kivy → Touch-friendly mobile apps‬


‭216‬

‭21.5 Projects – GUI Ultra Mega‬


‭1.‬ ‭Calculator App (Basic + Scientific)‬

‭2.‬ ‭To-Do List Manager (File-based)‬

‭3.‬ ‭Inventory Management System (Tkinter + SQLite)‬

‭4.‬ ‭Student Database GUI (CRUD operations)‬

‭5.‬ ‭Dashboard with Charts (Tkinter + Matplotlib/Plotly)‬

‭6.‬ ‭Desktop Weather App (API + Tkinter/PyQt)‬

‭21.6 Exercises – Tkinter Ultra Pro Max‬


‭1.‬ ‭Build a login window with username + password fields‬

‭2.‬ ‭Create a BMI calculator GUI‬

‭3.‬ ‭Make a list manager app with Add/Delete items‬

‭4.‬ ‭Build a table of students with Treeview, search functionality‬

‭5.‬ ‭Connect GUI to database → Insert, Update, Delete data‬

‭21.7 Summary – GUI God Mode‬


‭●‬ ‭GUI = Real user interaction‬

‭●‬ ‭Tkinter = Simple, fast‬

‭●‬ ‭PyQt / PySide = Professional desktop apps‬


‭217‬

‭●‬ ‭Kivy = Mobile apps‬

‭●‬ ‭Combine Backend + GUI + Database + API → Full-stack desktop applications‬

‭●‬ ‭Exercises → Build real apps to ingrain GUI concepts in bloodstream‬

‭ roject 1: Student Management System‬


P
‭(Desktop + Database GUI)‬
‭Features‬

‭●‬ ‭Add / Update / Delete student info‬

‭●‬ ‭Search students by name / ID‬

‭●‬ ‭Display in table (Treeview)‬

‭●‬ ‭Store data in SQLite database‬

‭●‬ ‭GUI using Tkinter‬

‭Folder Structure‬

student_management/‬

├─ [Link]‬

├─ [Link]‬

└─ [Link]‬

‭218‬

‭[Link]‬

import sqlite3‬

def create_db():‬

conn = [Link]("[Link]")‬

cursor = [Link]()‬

[Link]("""‬

CREATE TABLE IF NOT EXISTS students(‬


id INTEGER PRIMARY KEY AUTOINCREMENT,‬


name TEXT,‬

age INTEGER,‬

grade TEXT‬

)‬

""")‬

[Link]()‬

[Link]()‬

def add_student(name, age, grade):‬


conn = [Link]("[Link]")‬

cursor = [Link]()‬

‭[Link]("INSERT INTO students(name, age, grade) VALUES (?,‬


c
?, ?)", (name, age, grade))‬

[Link]()‬

‭219‬

[Link]()‬

def fetch_students():‬

conn = [Link]("[Link]")‬

cursor = [Link]()‬

[Link]("SELECT * FROM students")‬


data = [Link]()‬

[Link]()‬

return data‬

def delete_student(student_id):‬

conn = [Link]("[Link]")‬

cursor = [Link]()‬

[Link]("DELETE FROM students WHERE id=?", (student_id,))‬


[Link]()‬

[Link]()‬

‭[Link] (GUI)‬

import tkinter as tk‬


from tkinter import ttk, messagebox‬


‭rom database import create_db, add_student, fetch_students,‬


f
delete_student‬

‭220‬

create_db()‬

def add_student_gui():‬

name = name_entry.get()‬

age = age_entry.get()‬

grade = grade_entry.get()‬

if name and age and grade:‬


add_student(name, age, grade)‬


[Link]("Success", "Student Added!")‬


refresh_table()‬

else:‬

[Link]("Error", "Fill all fields!")‬


def refresh_table():‬

for row in tree.get_children():‬


[Link](row)‬

for student in fetch_students():‬


[Link]("", "end", values=student)‬


def delete_student_gui():‬

selected = [Link]()‬

if selected:‬

‭221‬

student_id = [Link](selected[0])['values'][0]‬

delete_student(student_id)‬

refresh_table()‬

‭[Link]("Deleted", "Student deleted‬


m
successfully!")‬

else:‬

[Link]("Error", "Select a student")‬


root = [Link]()‬

[Link]("Student Management System")‬


[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()‬

‭[Link](root, text="Add Student",‬


t
command=add_student_gui).pack(pady=10)‬

‭[Link](root, text="Delete Selected",‬


t
command=delete_student_gui).pack(pady=5)‬

# Table‬

‭ree = [Link](root, columns=("ID", "Name", "Age", "Grade"),‬


t
show="headings")‬

[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.‬

‭Project 2: Weather App + API + GUI‬


‭Features‬
‭223‬

‭●‬ ‭Fetch live weather from OpenWeatherMap API‬

‭●‬ ‭Input: city name‬

‭●‬ ‭Output: temperature, humidity, condition‬

‭●‬ ‭GUI using Tkinter‬

‭●‬ ‭JSON handling, API requests‬

‭Code: weather_app.py‬

import requests‬

import tkinter as tk‬


from tkinter import messagebox‬


API_KEY = "YOUR_API_KEY"‬

def get_weather():‬

city = city_entry.get()‬

if not city:‬

[Link]("Error", "Enter city name")‬


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:‬

[Link]("Error", "City not found")‬


root = [Link]()‬

[Link]("Weather App")‬

[Link]("400x300")‬

[Link](root, text="Enter City").pack(pady=10)‬


city_entry = [Link](root)‬

city_entry.pack()‬

[Link](root, text="Get Weather", command=get_weather).pack(pady=10)‬


result_label = [Link](root, text="", font=("Arial", 14))‬


result_label.pack(pady=20)‬

‭225‬

[Link]()‬

‭✅ Concepts used: API requests, JSON parsing, GUI, error handling, functions.‬

‭ roject 3: E-Commerce Product‬


P
‭Dashboard (GUI + Database + CRUD)‬
‭Features‬

‭●‬ ‭Manage product inventory‬

‭●‬ ‭Add, update, delete products‬

‭●‬ ‭Show in GUI table‬

‭●‬ ‭SQLite database integration‬

‭database_ecommerce.py‬

import sqlite3‬

def create_db():‬

conn = [Link]("[Link]")‬

cursor = [Link]()‬

[Link]("""‬

CREATE TABLE IF NOT EXISTS products(‬



‭226‬

id INTEGER PRIMARY KEY AUTOINCREMENT,‬


name TEXT,‬

price REAL,‬

quantity INTEGER‬

)‬

""")‬

[Link]()‬

[Link]()‬

def add_product(name, price, quantity):‬


conn = [Link]("[Link]")‬

cursor = [Link]()‬

[Link]("INSERT INTO products(name, price, quantity) VALUES‬



(?, ?, ?)", (name, price, quantity))‬

[Link]()‬

[Link]()‬

def fetch_products():‬

conn = [Link]("[Link]")‬

cursor = [Link]()‬

[Link]("SELECT * FROM products")‬


data = [Link]()‬

[Link]()‬

‭227‬

return data‬

def delete_product(product_id):‬

conn = [Link]("[Link]")‬

cursor = [Link]()‬

[Link]("DELETE FROM products WHERE id=?", (product_id,))‬


[Link]()‬

[Link]()‬

‭main_ecommerce.py (GUI)‬

import tkinter as tk‬


from tkinter import ttk, messagebox‬


‭rom database_ecommerce import create_db, add_product, fetch_products,‬


f
delete_product‬

create_db()‬

def add_product_gui():‬

name = name_entry.get()‬

price = price_entry.get()‬

qty = qty_entry.get()‬

if name and price and qty:‬



‭228‬

add_product(name, float(price), int(qty))‬


[Link]("Added", "Product added!")‬


refresh_table()‬

else:‬

[Link]("Error", "Fill all fields!")‬


def delete_product_gui():‬

selected = [Link]()‬

if selected:‬

product_id = [Link](selected[0])['values'][0]‬

delete_product(product_id)‬

refresh_table()‬

[Link]("Deleted", "Product deleted!")‬


else:‬

[Link]("Error", "Select a product")‬


def refresh_table():‬

for row in tree.get_children():‬


[Link](row)‬

for product in fetch_products():‬


[Link]("", "end", values=product)‬


root = [Link]()‬

‭229‬

[Link]("E-Commerce Product Dashboard")‬


[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()‬

‭[Link](root, text="Add Product",‬


t
command=add_product_gui).pack(pady=10)‬

‭[Link](root, text="Delete Selected",‬


t
command=delete_product_gui).pack(pady=5)‬

# Table‬

‭ree = [Link](root, columns=("ID", "Name", "Price", "Quantity"),‬


t
show="headings")‬

[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.‬

‭Project 4: Netflix Clone Desktop App‬


‭Features‬

‭1.‬ ‭User Authentication (Sign Up / Login)‬

‭2.‬ ‭Browse Movies / Shows‬

‭3.‬ ‭Movie Search by Name / Genre‬

‭4.‬ ‭Watch trailers (media playback)‬

‭5.‬ ‭Favorites / Watchlist‬

‭6.‬ ‭Store user & movie data in SQLite‬

‭7.‬ ‭GUI using Tkinter‬

‭8.‬ ‭API integration (The Movie Database API - TMDB)‬

‭9.‬ ‭Optional: Download poster images‬


‭231‬

‭Folder Structure‬

netflix_clone/‬

├─ [Link]‬

├─ [Link]‬

├─ [Link]‬

├─ media_player.py‬

├─ images/‬

└─ [Link]‬

‭[Link]‬

import sqlite3‬

def create_db():‬

conn = [Link]("[Link]")‬

cursor = [Link]()‬

[Link]("""‬

CREATE TABLE IF NOT EXISTS users(‬


id INTEGER PRIMARY KEY AUTOINCREMENT,‬


username TEXT UNIQUE,‬


password TEXT‬

)‬

‭232‬

""")‬

[Link]("""‬

CREATE TABLE IF NOT EXISTS favorites(‬


user_id INTEGER,‬

movie_id INTEGER,‬

movie_name TEXT,‬

PRIMARY KEY(user_id, movie_id)‬


)‬

""")‬

[Link]()‬

[Link]()‬

def add_user(username, password):‬


conn = [Link]("[Link]")‬

cursor = [Link]()‬

‭[Link]("INSERT INTO users(username, password) VALUES (?,‬


c
?)", (username, password))‬

[Link]()‬

[Link]()‬

def verify_user(username, password):‬



‭233‬

conn = [Link]("[Link]")‬

cursor = [Link]()‬

‭[Link]("SELECT * FROM users WHERE username=? AND‬


c
password=?", (username, password))‬

result = [Link]()‬

[Link]()‬

return result‬

def add_favorite(user_id, movie_id, movie_name):‬


conn = [Link]("[Link]")‬

cursor = [Link]()‬

‭[Link]("INSERT OR IGNORE INTO favorites(user_id, movie_id,‬


c
movie_name) VALUES (?, ?, ?)",‬

(user_id, movie_id, movie_name))‬


[Link]()‬

[Link]()‬

def fetch_favorites(user_id):‬

conn = [Link]("[Link]")‬

cursor = [Link]()‬

‭[Link]("SELECT movie_name FROM favorites WHERE user_id=?",‬


c
(user_id,))‬

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.‬

‭[Link] (GUI + Integration)‬

import tkinter as tk‬


from tkinter import ttk, messagebox‬


‭rom database import create_db, add_user, verify_user, add_favorite,‬


f
fetch_favorites‬

from api import search_movie, fetch_movie_details‬


from media_player import play_trailer‬


create_db()‬

current_user_id = None‬

‭236‬

def signup():‬

username = username_entry.get()‬

password = password_entry.get()‬

if username and password:‬


try:‬

add_user(username, password)‬

[Link]("Success", "Account created! Login‬



now.")‬

except:‬

[Link]("Error", "Username already exists.")‬


else:‬

[Link]("Error", "Fill all fields")‬


def login():‬

global current_user_id‬

username = username_entry.get()‬

password = password_entry.get()‬

user = verify_user(username, password)‬


if user:‬

[Link]("Success", f"Welcome {username}!")‬


current_user_id = user[0]‬

show_main_screen()‬

else:‬

‭237‬

[Link]("Error", "Invalid credentials")‬


def search():‬

query = search_entry.get()‬

movies = search_movie(query)‬

for row in movie_tree.get_children():‬


movie_tree.delete(row)‬

for m in movies:‬

‭ovie_tree.insert("", "end", values=(m["id"], m["title"],‬


m
m["release_date"]))‬

def add_to_favorites():‬

selected = movie_tree.selection()‬

if selected:‬

movie_id, name, _ = movie_tree.item(selected[0])['values']‬


add_favorite(current_user_id, movie_id, name)‬


[Link]("Added", f"{name} added to favorites!")‬


def show_main_screen():‬

login_frame.pack_forget()‬

main_frame.pack(expand=True, fill="both")‬

# --- GUI Setup ---‬



‭238‬

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 = [Link](login_frame, show="*")‬


password_entry.pack(pady=5)‬

[Link](login_frame, text="Login", command=login).pack(pady=5)‬


[Link](login_frame, text="Sign Up", command=signup).pack(pady=5)‬


main_frame = [Link](root)‬

[Link](main_frame, text="Search Movie").pack(pady=5)‬


search_entry = [Link](main_frame)‬

search_entry.pack(pady=5)‬

‭239‬

[Link](main_frame, text="Search", command=search).pack(pady=5)‬


columns = ("ID", "Title", "Release")‬


‭ovie_tree = [Link](main_frame, columns=columns,‬


m
show="headings")‬

for col in columns:‬


movie_tree.heading(col, text=col)‬

movie_tree.pack(expand=True, fill="both")‬

‭[Link](main_frame, text="Add to Favorites",‬


t
command=add_to_favorites).pack(pady=5)‬

[Link]()‬

‭✅ Concepts Covered in Project 4‬

‭1.‬ ‭User Authentication (Sign up / Login)‬

‭2.‬ ‭GUI design with Tkinter‬

‭3.‬ ‭Database CRUD operations (SQLite)‬

‭4.‬ ‭API requests & JSON parsing‬

‭5.‬ ‭Media handling (trailer playback)‬

‭6.‬ ‭OOP optional expansion‬

‭7.‬ ‭Loops, conditionals, functions, exception handling‬


‭240‬

‭8.‬ ‭Long, real-world desktop application‬

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.”‬

You might also like