Python
Basic to Advance
15 Din | Zero se Start | Data Analyst ke liye
Variables se Pandas tak — Hinglish Notes with Code Examples
Print se Pandas, NumPy, Matplotlib tak — sab kuch
BA / Any Graduate | Fresher Friendly | Real Code + Practice Tasks
15 Din ka Plan — Index
Din Topic Level Key Concepts
1 Python Setup + Hello World Beginner Install, IDLE, print, comments
2 Variables aur Data Types Beginner int, float, str, bool, type()
3 Strings — Deep Dive Beginner Slicing, methods, f-strings
4 Lists aur Tuples Beginner Index, slice, methods, loops
5 Dictionaries aur Sets Beginner+ Key-value, CRUD, set ops
6 Conditions — if/elif/else Beginner+ Branching, nested, ternary
7 Loops — for aur while Intermediate Range, enumerate, break, continue
8 Functions Intermediate def, args, kwargs, return, lambda
9 File Handling Intermediate Open, read, write, CSV, JSON
10 Error Handling Intermediate try/except, raise, custom errors
11 OOP — Classes aur Objects Advanced class, init, methods, inheritance
12 NumPy — Numerical Python Advanced Arrays, math, broadcasting
13 Pandas — Data Analysis Advanced DataFrame, read_csv, groupby
14 Matplotlib + Seaborn Advanced Plots, charts, visualizations
15 Mini Project + Review Advanced Full EDA project
Note: Roz ek din padho + VS Code ya Google Colab mein practice karo. Roz 1 ghanta kaafi hai. Code khud type
karo — copy-paste mat karo!
Python 15-Day Notes | Page 2
DAY 1
Python Setup + Hello World
Python install karo aur pehla program chalao
Python kya hai?
Python ek programming language hai jo bahut easy aur readable hai. Data analysis, machine learning,
web development — sab mein use hoti hai. Data analyst ke liye Python = supercharged Excel. Pandas
library se lakhs rows ka data seconds mein analyze ho jaata hai.
Installation:
• [Link] pe jaao — Latest version download karo
• Install karte waqt 'Add Python to PATH' checkbox zaroor tick karo
• VS Code download karo — [Link] — best editor
• Ya Google Colab use karo — [Link] — kuch install nahi!
Pehla Program:
# Yeh Python ka pehla program hai
# # se comment shuru hota hai — Python ignore karta hai
print("Hello, World!")
>>> Hello, World!
print("Mera naam Ram hai")
print("Main Python seekh raha hoon")
# Multiple values print karo
print("Name:", "Ram", "Age:", 22)
>>> Name: Ram Age: 22
# sep aur end parameters
print("A", "B", "C", sep="-")
>>> A-B-C
print("Hello", end=" ")
print("World")
>>> Hello World
Python Calculator — Basic Math:
print(10 + 5) # Addition => 15
print(10 - 3) # Subtraction => 7
print(4 * 6) # Multiply => 24
print(15 / 4) # Division => 3.75
print(15 // 4) # Floor div => 3
print(15 % 4) # Modulus => 3
print(2 ** 10) # Power => 1024
Tip: Google Colab sabse best hai beginners ke liye — browser mein kholao, code likhao, Run karo. Kuch install nahi
karna. [Link]
Python 15-Day Notes | Page 3
Aaj ka Practice:
1. Python install karo ya Google Colab kholao
2. Hello World print karo
3. Apna naam aur city print karo
4. Calculator: 2 numbers add, subtract, multiply karo
5. 2 ka 10th power calculate karo
Aaj kya seekha:
✓ Python install kiya
✓ print() function samjha
✓ Basic math operations aate hain
✓ Comments likhna aaya
Python 15-Day Notes | Page 4
DAY 2
Variables aur Data Types
Data store karna aur types samajhna
Variable kya hai?
Variable ek naam hai jisme value store hoti hai. Jaise ek box jisme kuch rakha ho. Python mein type
declare nahi karna — automatically samajh jaata hai.
# Variable banana
name = 'Ram Kumar'
age = 22
salary = 35000.50
is_employed = True
# Print karo
print(name) # Ram Kumar
print(age) # 22
print(type(age)) #
4 Main Data Types:
Type Kya store karta hai Example
int Integer numbers age = 22
float Decimal numbers salary = 35000.50
str Text/String name = 'Ram'
bool True ya False is_active = True
NoneType Koi value nahi result = None
# Type check karo
print(type(22)) # int
print(type(22.5)) # float
print(type("Hello")) # str
print(type(True)) # bool
print(type(None)) # NoneType
# Type conversion
print(int("42")) # 42
print(float("3.14")) # 3.14
print(str(100)) # "100"
print(bool(0)) # False
print(bool(1)) # True
print(bool('')) # False
print(bool("hello")) # True
Python 15-Day Notes | Page 5
Input lena user se:
# input() hamesha string return karta hai
name = input("Apna naam daalo: ")
print("Hello,", name)
# Number input ke liye convert karo
age = int(input("Umar daalo: "))
print("Agla saal umar hogi:", age + 1)
Multiple Assignment aur Swap:
# Ek saath multiple variables
x, y, z = 10, 20, 30
a = b = c = 0
# Values swap karo — Python mein easy!
a, b = 5, 10
a, b = b, a
print(a, b) # 10 5
Common Mistake: Variable names mein space nahi hota. 'my name' galat hai, 'my_name' sahi hai. Numbers se
shuru nahi kar sakte: '2name' galat.
Aaj ka Practice:
1. Apna naam, age, city variables mein store karo
2. type() se sab check karo
3. User se naam lo aur greeting print karo
4. Do numbers ka sum, difference, product nikalo
5. Age ko float mein convert karo
Aaj kya seekha:
✓ Variables clearly samjhe
✓ 4 data types pata hain
✓ Type conversion aata hai
✓ Input lena aaya
Python 15-Day Notes | Page 6
DAY 3
Strings — Deep Dive
Text ke saath kaam karna
String create karna:
s1 = 'Single quotes'
s2 = "Double quotes"
s3 = """Triple quotes
multiline string"""
# String repeat
print("Ha" * 3) # HaHaHa
# String length
print(len("Hello")) # 5
Indexing aur Slicing:
name = "Python"
# Index: 0 1 2 3 4 5
# Reverse:-6-5-4-3-2-1
print(name[0]) # P (pehla character)
print(name[-1]) # n (aakhri character)
print(name[1:4]) # yth (index 1 se 3 tak)
print(name[:3]) # Pyt (start se 3 tak)
print(name[2:]) # thon (2 se end tak)
print(name[::2]) # Pto (har 2nd character)
print(name[::-1]) # nohtyP (reverse!)
Important String Methods:
Method Kya karta hai Example
.upper() Sab capital 'hello'.upper() => 'HELLO'
.lower() Sab small 'HELLO'.lower() => 'hello'
.title() Har word capital 'ram kumar'.title()
.strip() Side spaces hatao ' hi '.strip() => 'hi'
.split() List mein tod do 'a,b,c'.split(',')
.join() List se string banao ','.join(['a','b'])
.replace() Replace karo 'hello'.replace('l','r')
.find() Position nikalo 'hello'.find('ll') => 2
.count() Count karo 'hello'.count('l') => 2
.startswith() Se shuru hota hai 'Ram'.startswith('R')
Python 15-Day Notes | Page 7
.endswith() Pe khatam hota hai 'Ram'.endswith('m')
.isdigit() Sirf numbers hain? '123'.isdigit() => True
.isalpha() Sirf letters hain? 'abc'.isalpha() => True
f-strings — Modern Way to Format:
name = 'Ram'
age = 22
salary = 35000.5
# f-string — sabse easy!
print(f"Mera naam {name} hai aur main {age} saal ka hoon")
>>> Mera naam Ram hai aur main 22 saal ka hoon
# Calculation inside f-string
print(f"Annual salary: {salary * 12:,.0f}")
>>> Annual salary: 4,20,006
# Format specifiers
print(f"Pi = {3.14159:.2f}") # Pi = 3.14
print(f"Score: {0.856:.1%}") # Score: 85.6%
print(f"ID: {42:05d}") # ID: 00042
Tip: f-strings Python 3.6+ mein available hain aur sabse readable hain. Data analysis mein output format karne ke
liye daily use hote hain.
Aaj ka Practice:
1. Apna full name — reverse karo slicing se
2. Email se username nikalo (@ se pehle wala)
3. Sentence ke words count karo — split + len
4. f-string se apna bio print karo
5. String palindrome hai ya nahi check karo
Aaj kya seekha:
✓ String indexing/slicing aata hai
✓ String methods clearly aate hain
✓ f-strings use karna aaya
Python 15-Day Notes | Page 8
DAY 4
Lists aur Tuples
Collection data types
List kya hai?
List ordered collection hai jisme multiple values store hoti hain. Changeable (mutable) hai. Data analyst ke
liye rows of data jaisi hoti hai.
# List banana
fruits = ['apple', 'banana', 'mango']
numbers = [1, 2, 3, 4, 5]
mixed = [1, 'Ram', 3.14, True] # Mixed types OK
# Access karo
print(fruits[0]) # apple
print(fruits[-1]) # mango
print(fruits[1:3]) # ['banana', 'mango']
# Modify karo
fruits[0] = 'grapes'
print(fruits) # ['grapes', 'banana', 'mango']
Important List Methods:
Method Kya karta hai Example
.append(x) End mein add [Link]('new')
.insert(i,x) Position pe insert [Link](1,'val')
.extend(lst) Dusri list add karo [Link]([4,5])
.remove(x) Value hataao [Link]('apple')
.pop(i) Index se hatao + return [Link](0)
.sort() Sort karo (in-place) [Link]()
.reverse() Ulta karo [Link]()
.index(x) Position dhundho [Link]('a')
.count(x) Count karo [Link](1)
len(lst) Length nikalo len(fruits)
sorted(lst) Naya sorted list sorted(numbers)
sum(lst) Sum karo sum([1,2,3]) => 6
min/max(lst) Min/Max nikalo min([3,1,2]) => 1
List Comprehension — Powerful One-liner:
Python 15-Day Notes | Page 9
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# Normal loop se even numbers
evens = []
for n in numbers:
if n % 2 == 0:
[Link](n)
# List comprehension se — same kaam ek line mein!
evens = [n for n in numbers if n % 2 == 0]
print(evens) # [2, 4, 6, 8, 10]
# Squares nikalo
squares = [x**2 for x in range(1, 6)]
print(squares) # [1, 4, 9, 16, 25]
# Names uppercase mein
names = ['ram', 'priya', 'suresh']
upper_names = [[Link]() for n in names]
Tuple — Immutable List:
# Tuple — change nahi ho sakta
coords = (28.6, 77.2) # Delhi coordinates
colors = ('red', 'green', 'blue')
# Access same as list
print(coords[0]) # 28.6
# Tuple unpacking
lat, lon = coords
print(f"Lat: {lat}, Lon: {lon}")
# Tuple as dictionary key (list nahi ho sakta)
locations = {(28.6, 77.2): 'Delhi', (19.0, 72.8): 'Mumbai'}
Common Mistake: List mein .sort() in-place sort karta hai aur None return karta hai. sorted() naya list return karta
hai. result = [Link]() galat pattern hai.
Aaj ka Practice:
1. 10 cities ki list banao — sort karo, reverse karo
2. List mein add, remove, insert operations karo
3. List comprehension se 1-20 ke cubes nikalo
4. Marks list se 60+ wale students filter karo
5. Two lists ko merge karo — extend use karo
Aaj kya seekha:
✓ List operations clearly aate hain
✓ List comprehension samjha
✓ Tuple aur immutability pata hai
Python 15-Day Notes | Page 10
DAY 5
Dictionaries aur Sets
Key-Value pairs aur Unique collections
Dictionary — Key-Value Store:
# Dictionary banana
student = {
'name': 'Ram Kumar',
'age': 22,
'city': 'Delhi',
'marks': [85, 92, 78]
}
# Access karo
print(student['name']) # Ram Kumar
print([Link]('age')) # 22
print([Link]('phone', 'N/A')) # N/A (default)
# Add/Update
student['email'] = 'ram@[Link]'
student['age'] = 23
# Delete
del student['city']
[Link]('email')
Dictionary Methods:
# Keys, values, items
print([Link]()) # dict_keys(['name', 'age',...])
print([Link]()) # dict_values(['Ram', 22,...])
print([Link]()) # dict_items([('name','Ram'),...])
# Loop karo
for key, value in [Link]():
print(f"{key}: {value}")
# Check key exist karta hai
print('name' in student) # True
print('phone' in student) # False
# Dict comprehension
squares = {x: x**2 for x in range(1, 6)}
print(squares) # {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
Nested Dictionary:
Python 15-Day Notes | Page 11
# Real-world example: Students database
students = {
101: {'name': 'Ram', 'marks': 85, 'city': 'Delhi'},
102: {'name': 'Priya', 'marks': 92, 'city': 'Mumbai'},
103: {'name': 'Ravi', 'marks': 78, 'city': 'Delhi'},
}
# Access
print(students[101]['name']) # Ram
print(students[102]['marks']) # 92
Sets — Unique Values:
# Set — duplicate nahi hote
cities = {'Delhi', 'Mumbai', 'Delhi', 'Chennai'}
print(cities) # {'Delhi', 'Mumbai', 'Chennai'}
# Set operations
a = {1, 2, 3, 4}
b = {3, 4, 5, 6}
print(a | b) # Union: {1,2,3,4,5,6}
print(a & b) # Intersection: {3,4}
print(a - b) # Difference: {1,2}
print(a ^ b) # Symmetric diff: {1,2,5,6}
# Duplicates remove karna
names = ['Ram', 'Priya', 'Ram', 'Suresh']
unique = list(set(names))
print(len(names), len(unique)) # 4 3
Tip: Dictionary Data Analyst ka best friend hai. JSON data (APIs se aata hai) dictionary jaisa hota hai. Ek baar
samajh lo — API data handle karna easy ho jaayega.
Aaj ka Practice:
1. Apna profile dictionary banao — 6+ keys
2. Dictionary ko loop karo — sab print karo
3. Nested dict: 5 students ka database
4. List se duplicates hatao — set use karo
5. Word frequency count karo — dict use karo
Aaj kya seekha:
✓ Dictionary CRUD operations aate hain
✓ Nested dict samjha
✓ Set operations pata hain
✓ Dict comprehension aaya
Python 15-Day Notes | Page 12
DAY 6
Conditions — if/elif/else
Decision making in Python
if/elif/else — Basic Structure:
marks = 75
if marks >= 90:
print("A Grade")
elif marks >= 75:
print("B Grade")
elif marks >= 60:
print("C Grade")
elif marks >= 50:
print("D Grade")
else:
print("Fail")
>>> B Grade
# Important: Python mein indentation (4 spaces) zaroori hai!
# Colon (:) zaroor lagao condition ke baad
Comparison aur Logical Operators:
Operator Matlab Example
== Barabar x == 10
!= Barabar nahi x != 0
> < Greater/Less x>5
>= <= Greater/Less equal x >= 18
and Dono true x>0 and x<100
or Koi ek true x<0 or x>100
not Ulta not(x == 0)
in List mein hai 'a' in 'apple'
not in List mein nahi x not in [1,2,3]
is Same object x is None
is not Different object x is not None
Ternary Operator — One Line if/else:
Python 15-Day Notes | Page 13
# Normal
if age >= 18:
status = 'Adult'
else:
status = 'Minor'
# Ternary — same kaam ek line mein
status = 'Adult' if age >= 18 else 'Minor'
print(status)
# Practical examples
result = 'Pass' if marks >= 50 else 'Fail'
discount = 0.2 if total > 1000 else 0.1
Nested Conditions + Real Examples:
# Login system
username = 'admin'
password = '1234'
if username == 'admin':
if password == '1234':
print("Login successful!")
else:
print("Wrong password")
else:
print("User not found")
# Same — cleaner way
if username == 'admin' and password == '1234':
print("Login successful!")
else:
print("Login failed")
Common Mistake: Python mein = assignment hai, == comparison hai. if x = 5 galat hai, if x == 5 sahi hai. Yeh bahut
common mistake hai beginners ki.
Aaj ka Practice:
1. Marks ke hisaab se grade assign karo (A/B/C/D/F)
2. Number positive, negative ya zero hai check karo
3. Simple calculator — user se 2 numbers aur operation lo
4. FizzBuzz: 1-20 tak — 3 ka multiple Fizz, 5 ka Buzz, dono ka FizzBuzz
5. Year leap year hai ya nahi check karo
Aaj kya seekha:
✓ if/elif/else clearly aata hai
✓ Operators pata hain
✓ Ternary operator samjha
✓ Nested conditions likhna aaya
Python 15-Day Notes | Page 14
DAY 7
Loops — for aur while
Repetitive tasks automate karna
for Loop:
# List pe loop
fruits = ['apple', 'banana', 'mango']
for fruit in fruits:
print(f"Fruit: {fruit}")
# range() se numbers
for i in range(5): # 0,1,2,3,4
print(i)
for i in range(1, 11): # 1 se 10
print(i)
for i in range(0, 20, 2): # 0,2,4,...18 (step=2)
print(i)
# String pe loop
for char in "Python":
print(char)
# Dict pe loop
student = {'name': 'Ram', 'age': 22}
for key, val in [Link]():
print(f"{key} = {val}")
enumerate() aur zip():
# enumerate — index bhi chahiye saath
names = ['Ram', 'Priya', 'Ravi']
for i, name in enumerate(names, start=1):
print(f"{i}. {name}")
>>> 1. Ram
>>> 2. Priya
>>> 3. Ravi
# zip — do lists saath loop karo
names = ['Ram', 'Priya', 'Ravi']
scores = [85, 92, 78]
for name, score in zip(names, scores):
print(f"{name}: {score}")
while Loop:
Python 15-Day Notes | Page 15
# while — condition true rehne tak chalega
count = 1
while count <= 5:
print(f"Count: {count}")
count += 1
# break — loop rokna
for i in range(100):
if i == 5:
break
print(i)
# Output: 0 1 2 3 4
# continue — current iteration skip karo
for i in range(10):
if i % 2 == 0:
continue
print(i) # Sirf odd: 1 3 5 7 9
Nested Loops:
# Multiplication table
for i in range(1, 4):
for j in range(1, 4):
print(f"{i}x{j}={i*j}", end=" ")
print() # New line
# List of lists process karo
matrix = [[1,2,3],[4,5,6],[7,8,9]]
for row in matrix:
for val in row:
print(val, end=" ")
print()
Tip: for loop use karo jab pata ho kitni baar chalana hai. while loop use karo jab condition pe depend ho. Infinite loop
se bachne ke liye while mein hamesha exit condition rakho.
Aaj ka Practice:
1. 1 se 100 tak sum nikalo — for loop
2. Marks list mein se passing (50+) students count karo
3. Multiplication table print karo — nested loop
4. List mein se duplicates hatao — loop use karo
5. Password guess game — while loop (max 3 tries)
Python 15-Day Notes | Page 16
Aaj kya seekha:
✓ for loop clearly aata hai
✓ range(), enumerate(), zip() pata hai
✓ while, break, continue samjha
✓ Nested loops likhna aaya
Python 15-Day Notes | Page 17
DAY 8
Functions
Reusable code blocks banana
Function kya hai?
Function ek named code block hai jo ek specific kaam karta hai. Ek baar likho, baar baar use karo. Code
organized aur reusable rehta hai.
# Function define karo
def greet(name):
return f"Hello, {name}!"
# Call karo
print(greet("Ram")) # Hello, Ram!
print(greet("Priya")) # Hello, Priya!
# Multiple parameters
def add(a, b):
return a + b
print(add(5, 3)) # 8
print(add(10, 20)) # 30
Default Parameters aur Keyword Arguments:
# Default value — argument nahi diya toh default use hoga
def greet(name, msg='Good Morning'):
return f"{msg}, {name}!"
print(greet("Ram")) # Good Morning, Ram!
print(greet("Priya", "Good Night")) # Good Night, Priya!
# Keyword arguments — order matter nahi karta
def info(name, age, city):
print(f"{name}, {age}, {city}")
info(age=22, city='Delhi', name='Ram')
*args aur **kwargs:
Python 15-Day Notes | Page 18
# *args — kitne bhi positional arguments
def total(*numbers):
return sum(numbers)
print(total(1, 2, 3)) # 6
print(total(10, 20, 30, 40)) # 100
# **kwargs — keyword arguments as dictionary
def profile(**details):
for k, v in [Link]():
print(f"{k}: {v}")
profile(name='Ram', age=22, city='Delhi')
Lambda Functions:
# Lambda — anonymous one-line function
square = lambda x: x**2
print(square(5)) # 25
add = lambda a, b: a + b
print(add(3, 4)) # 7
# Sorting ke saath useful
students = [('Ram', 85), ('Priya', 92), ('Ravi', 78)]
[Link](key=lambda x: x[1], reverse=True)
print(students) # Priya first (highest marks)
# map() aur filter() ke saath
nums = [1, 2, 3, 4, 5]
squares = list(map(lambda x: x**2, nums))
evens = list(filter(lambda x: x%2==0, nums))
Scope — Local vs Global:
x = 10 # Global variable
def func():
y = 20 # Local variable
print(x) # Global access kar sakte hain
print(y)
func()
# print(y) # ERROR! y local hai
# Global variable modify karna
count = 0
def increment():
global count
count += 1
Tip: Functions chote rakho — ek function ek kaam kare. Agar function 20 lines se bada ho raha hai, usse tod do.
Data analysis mein har step ke liye alag function banao.
Python 15-Day Notes | Page 19
Aaj ka Practice:
1. Calculator function banao — operation parameter se
2. List ka average nikalne ka function
3. Palindrome check function
4. Fibonacci series function
5. Lambda se marks ke hisaab se students sort karo
Aaj kya seekha:
✓ Functions define aur call karna aaya
✓ Default args, *args, **kwargs pata hain
✓ Lambda functions samjhe
✓ Scope concept clear hai
Python 15-Day Notes | Page 20
DAY 9
File Handling + CSV + JSON
Files padhna aur likhna
File Operations:
# File kholna — modes
# 'r' = read, 'w' = write, 'a' = append, 'rb' = read binary
# File likhna
with open('[Link]', 'w') as f:
[Link]("Hello World\n")
[Link]("Python is great\n")
# File padhna
with open('[Link]', 'r') as f:
content = [Link]() # Sab ek saath
print(content)
# Line by line padhna
with open('[Link]', 'r') as f:
for line in f:
print([Link]())
# Lines as list
with open('[Link]', 'r') as f:
lines = [Link]()
CSV Files — Data Analyst ka Kaam:
import csv
# CSV likhna
data = [
['Name', 'Age', 'City', 'Salary'],
['Ram', 22, 'Delhi', 50000],
['Priya', 25, 'Mumbai', 65000],
['Ravi', 28, 'Bangalore', 72000]
]
with open('[Link]', 'w', newline='') as f:
writer = [Link](f)
[Link](data)
# CSV padhna
with open('[Link]', 'r') as f:
reader = [Link](f)
for row in reader:
print(row["Name"], row["Salary"])
JSON — API Data Handle karna:
Python 15-Day Notes | Page 21
import json
# Python dict se JSON
data = {
'name': 'Ram',
'skills': ['Python', 'SQL', 'Excel'],
'experience': 2
}
json_str = [Link](data, indent=2)
print(json_str)
# JSON file mein save karo
with open('[Link]', 'w') as f:
[Link](data, f, indent=2)
# JSON file padhna
with open('[Link]', 'r') as f:
loaded = [Link](f)
print(loaded['name']) # Ram
print(loaded['skills']) # ['Python', 'SQL', 'Excel']
Tip: with statement use karo file kholne ke liye — automatically close ho jaati hai. Manually [Link]() likhne ki
zaroorat nahi.
Aaj ka Practice:
1. 10 students ka data CSV file mein likho
2. Wahi CSV file padho aur average marks nikalo
3. JSON file mein apna profile save karo
4. CSV se highest salary wala employee nikalo
5. Multiple CSV files ko ek mein merge karo
Aaj kya seekha:
✓ File read/write aata hai
✓ CSV padhna likhna aaya
✓ JSON handle karna aaya
✓ with statement use karna aaya
Python 15-Day Notes | Page 22
DAY 10
Error Handling
try/except — Errors ko gracefully handle karna
Errors kyu aate hain?
# Common Python errors
print(10 / 0) # ZeroDivisionError
print(int('hello')) # ValueError
print(undefined_var) # NameError
lst = [1,2,3]
print(lst[10]) # IndexError
d = {'a': 1}
print(d['z']) # KeyError
try/except — Error Handle Karna:
# Basic try/except
try:
result = 10 / 0
print(result)
except ZeroDivisionError:
print("Error: Zero se divide nahi kar sakte!")
# Multiple exceptions
try:
num = int(input("Number daalo: "))
result = 100 / num
print(result)
except ValueError:
print("Sirf number daalo!")
except ZeroDivisionError:
print("Zero mat daalo!")
except Exception as e:
print(f"Koi aur error: {e}")
# else aur finally
try:
f = open('[Link]', 'r')
data = [Link]()
except FileNotFoundError:
print("File nahi mili!")
else:
print("File successfully read!")
finally:
print("Yeh hamesha chalega")
Python 15-Day Notes | Page 23
Common Python Errors Quick Reference:
Error Kab aata hai Fix
SyntaxError Galat syntax Colon, brackets check karo
IndentationError Galat indentation 4 spaces use karo
NameError Variable defined nahi Spelling check karo
TypeError Wrong type Type conversion karo
ValueError Wrong value Input validate karo
IndexError List range se bahar len() check karo pehle
KeyError Dict key nahi hai [Link]() use karo
ZeroDivisionError Zero se divide if divisor != 0 check
FileNotFoundError File nahi hai Path check karo
ImportError Module nahi mila pip install karo
AttributeError Method nahi hai Type check karo
Custom Exception aur raise:
# Custom exception define karo
class AgeError(Exception):
pass
def check_age(age):
if age < 0 or age > 150:
raise AgeError(f"Invalid age: {age}")
return f"Valid age: {age}"
try:
print(check_age(-5))
except AgeError as e:
print(f"Error: {e}")
Tip: Production code mein bare except: mat use karo — specific exceptions pakdo. Data analysis scripts mein
logging add karo taaki errors track ho sakein.
Aaj ka Practice:
1. Division function banao — ZeroDivisionError handle karo
2. File reading — FileNotFoundError handle karo
3. User input — ValueError handle karo (string ki jagah number diya)
4. Age validation custom exception se
5. Safe dictionary lookup function — KeyError handle karo
Python 15-Day Notes | Page 24
Aaj kya seekha:
✓ try/except clearly aata hai
✓ Common errors pata hain
✓ finally samjha
✓ Custom exceptions banana aaya
Python 15-Day Notes | Page 25
DAY 11
OOP — Classes aur Objects
Object Oriented Programming basics
OOP kya hai?
OOP mein hum real-world cheezein code mein represent karte hain. Class ek blueprint hai, Object ek
actual instance hai. Data analyst ke liye custom data structures banana hota hai.
# Class define karo
class Student:
# __init__ = constructor (object banane par chalata hai)
def __init__(self, name, age, marks):
[Link] = name
[Link] = age
[Link] = marks
def grade(self):
if [Link] >= 90: return 'A'
elif [Link] >= 75: return 'B'
elif [Link] >= 60: return 'C'
else: return 'F'
def __str__(self):
return f"Student: {[Link]}, Marks: {[Link]}"
# Objects banana
s1 = Student('Ram', 22, 85)
s2 = Student('Priya', 20, 92)
print([Link]) # Ram
print([Link]()) # B
print(s1) # Student: Ram, Marks: 85
Inheritance — Parent se Child:
Python 15-Day Notes | Page 26
class Person:
def __init__(self, name, age):
[Link] = name
[Link] = age
def introduce(self):
return f"Hi, I am {[Link]}"
class Employee(Person): # Person se inherit
def __init__(self, name, age, salary):
super().__init__(name, age) # Parent init call
[Link] = salary
def details(self):
return f"{[Link]()}, Salary: {[Link]}"
emp = Employee('Ram', 25, 50000)
print([Link]())
Class Methods aur Static Methods:
class DataProcessor:
total_processed = 0 # Class variable
def __init__(self, data):
[Link] = data
DataProcessor.total_processed += 1
@classmethod
def get_count(cls):
return cls.total_processed
@staticmethod
def clean(text):
return [Link]().lower()
d1 = DataProcessor([1,2,3])
d2 = DataProcessor([4,5,6])
print(DataProcessor.get_count()) # 2
print([Link](" HELLO ")) # hello
Tip: Data Analysis mein OOP zyada use nahi hota directly — but Pandas DataFrame ek class hai, scikit-learn
models classes hain. OOP samajhna libraries use karne mein help karta hai.
Aaj ka Practice:
1. BankAccount class banao — deposit, withdraw, balance methods
2. Product class — name, price, discount_price property
3. Employee inheritance from Person class
4. Library system — Book aur Library classes
5. DataSet class — load_csv, describe, filter methods
Python 15-Day Notes | Page 27
Aaj kya seekha:
✓ Class aur Object banana aata hai
✓ __init__ samjha
✓ Inheritance clearly aaya
✓ Class vs static methods pata hain
Python 15-Day Notes | Page 28
DAY 12
NumPy — Numerical Python
Fast array operations for data analysis
NumPy kyun? Python list se better?
NumPy arrays Python lists se 10-100x fast hote hain math operations ke liye. Pandas ke andar NumPy hi
kaam karta hai. Data analysis ke liye essential library hai.
import numpy as np
# Array banana
arr = [Link]([1, 2, 3, 4, 5])
print(arr) # [1 2 3 4 5]
print([Link]) # int64
print([Link]) # (5,)
# 2D array (matrix)
matrix = [Link]([[1,2,3],[4,5,6],[7,8,9]])
print([Link]) # (3, 3)
print(matrix[1][2]) # 6
print(matrix[0,:]) # [1 2 3] (pehli row)
print(matrix[:,1]) # [2 5 8] (doosra column)
# Special arrays
print([Link]((3,3))) # 3x3 zeros
print([Link]((2,4))) # 2x4 ones
print([Link](0,10,2)) # [0 2 4 6 8]
print([Link](0,1,5)) # 5 equal points
print([Link](3,3)) # Random 3x3
Array Operations — Fast Math:
Python 15-Day Notes | Page 29
a = [Link]([1, 2, 3, 4, 5])
b = [Link]([10, 20, 30, 40, 50])
# Element-wise operations
print(a + b) # [11 22 33 44 55]
print(a * b) # [10 40 90 160 250]
print(a ** 2) # [ 1 4 9 16 25]
print(b / a) # [10. 10. 10. 10. 10.]
# Statistical functions
data = [Link]([85, 92, 78, 95, 88, 72, 90])
print([Link](data)) # 85.71
print([Link](data)) # 88.0
print([Link](data)) # 7.82
print([Link](data)) # 72
print([Link](data)) # 95
print([Link](data)) # 600
print([Link](data, 75)) # 75th percentile
Filtering aur Boolean Indexing:
scores = [Link]([55, 82, 45, 91, 67, 78, 88])
# Boolean mask
passing = scores >= 60
print(passing) # [False True False True ...]
print(scores[passing]) # [82 91 67 78 88]
# One-liner
print(scores[scores > 80]) # [82 91 88]
# Where function
result = [Link](scores >= 60, 'Pass', 'Fail')
print(result)
Tip: NumPy broadcasting bahut powerful hai — alag shapes ke arrays pe operations. Pandas mein sab NumPy pe
built hai, isliye NumPy samajhna Pandas ko easier banata hai.
Aaj ka Practice:
1. 100 random numbers ka array — mean, std, min, max nikalo
2. Matrix multiplication — [Link]() use karo
3. Scores array se failing students nikalo
4. 2D sales matrix ka row-wise aur column-wise sum
5. [Link]() se Pass/Fail labels banao
Aaj kya seekha:
✓ NumPy arrays aate hain
✓ Statistical functions clearly aate hain
✓ Boolean indexing samjha
✓ Broadcasting concept pata hai
Python 15-Day Notes | Page 30
DAY 13
Pandas — Data Analysis Library
DataFrame se real data analysis karna
Pandas kya hai?
Pandas Python ka Excel hai — but 1000x powerful. DataFrame ek 2D table hai jisme rows aur columns
hote hain. Data analyst ka sabse important Python tool.
import pandas as pd
import numpy as np
# DataFrame banana
data = {
'Name': ['Ram', 'Priya', 'Ravi', 'Anita'],
'Age': [22, 25, 28, 23],
'City': ['Delhi', 'Mumbai', 'Delhi', 'Chennai'],
'Salary': [50000, 65000, 72000, 58000]
}
df = [Link](data)
print(df)
# CSV se load karo (most common!)
df = pd.read_csv('[Link]')
df = pd.read_excel('[Link]')
# Basic info
print([Link]) # (rows, columns)
print([Link]) # Column names
print([Link]) # Data types
print([Link]()) # Full summary
print([Link]()) # Statistics
print([Link](5)) # Pehli 5 rows
print([Link](3)) # Aakhri 3 rows
Selecting Data:
Python 15-Day Notes | Page 31
# Column select
print(df['Name']) # Ek column (Series)
print(df[['Name', 'Salary']]) # Multiple columns
# Row select
print([Link][0]) # Index se (0-based)
print([Link][1:4]) # Slice
print([Link][0]) # Label se
# Filtering
delhi = df[df['City'] == 'Delhi']
high_sal = df[df['Salary'] > 60000]
young_delhi = df[(df['City']=='Delhi') & (df['Age'] < 25)]
Common Pandas Operations:
# New column add karo
df['Annual'] = df['Salary'] * 12
df['Grade'] = df['Salary'].apply(lambda x: 'High' if x>60000 else 'Low')
# Sort karo
df_sorted = df.sort_values('Salary', ascending=False)
# Group by
city_stats = [Link]('City')['Salary'].agg(['mean','min','max','count'])
print(city_stats)
# Missing values
print([Link]().sum()) # Null count per column
[Link](0, inplace=True) # Fill with 0
[Link](inplace=True) # Drop rows with nulls
# Duplicates
df.drop_duplicates(inplace=True)
# Save karo
df.to_csv('[Link]', index=False)
Tip: [Link]() ek command se mean, std, min, max, quartiles sab deta hai. Kisi bhi naye dataset pe pehla kaam
yahi karo!
Aaj ka Practice:
1. Kaggle se koi CSV download karo aur load karo
2. describe() aur info() se dataset samjho
3. City-wise average salary groupby se nikalo
4. Missing values handle karo
5. Top 5 highest salary wale employees nikalo
Python 15-Day Notes | Page 32
Aaj kya seekha:
✓ DataFrame banana aur load karna aaya
✓ Filtering clearly aata hai
✓ groupby aur aggregation aaya
✓ Missing values handle karna aaya
Python 15-Day Notes | Page 33
DAY 14
Matplotlib + Seaborn
Data Visualization in Python
Visualization kyun zaroori hai?
Numbers dekhna mushkil hai. Chart se pattern instantly samajh aata hai. Python mein charts banao aur
directly report ya presentation mein use karo.
import [Link] as plt
import seaborn as sns
import pandas as pd
# --- MATPLOTLIB BASICS ---
# Line plot
months = ['Jan','Feb','Mar','Apr','May','Jun']
sales = [45000, 52000, 49000, 61000, 58000, 72000]
[Link](figsize=(10, 5))
[Link](months, sales, marker='o', color='blue', linewidth=2)
[Link]('Monthly Sales Trend')
[Link]('Month')
[Link]('Sales (Rs)')
[Link](True)
plt.tight_layout()
[Link]('sales_trend.png') # Save karo
[Link]()
# Bar chart
cities = ['Delhi', 'Mumbai', 'Bangalore', 'Chennai']
revenue = [85000, 95000, 72000, 68000]
[Link](figsize=(8, 5))
bars = [Link](cities, revenue, color=['#2E86C1','#1D9E75','#854F0B','#534AB7'])
plt.bar_label(bars, fmt='%.0f') # Labels on bars
[Link]('City-wise Revenue')
[Link]('Revenue (Rs)')
[Link]()
# Pie chart
categories = ['Electronics', 'Clothing', 'Food', 'Books']
values = [35, 28, 22, 15]
[Link](figsize=(7, 7))
[Link](values, labels=categories, autopct='%1.1f%%',
startangle=90, explode=[0.05,0,0,0])
[Link]('Sales by Category')
[Link]()
Python 15-Day Notes | Page 34
Seaborn — Beautiful Statistical Plots:
import seaborn as sns
# Seaborn built-in datasets
df = sns.load_dataset('iris')
# Distribution plot
[Link](df['sepal_length'], bins=20, kde=True)
[Link]('Sepal Length Distribution')
[Link]()
# Box plot — outliers dekhna
[Link](x='species', y='sepal_length', data=df)
[Link]()
# Correlation heatmap — Data Analyst ka fav!
[Link](figsize=(10, 8))
[Link]([Link](numeric_only=True), annot=True,
cmap='coolwarm', fmt='.2f')
[Link]('Correlation Matrix')
[Link]()
# Scatter plot with regression line
[Link](x='sepal_length', y='petal_length', data=df)
[Link]()
Tip: Seaborn + Pandas = perfect combo. df se directly seaborn mein data daal sakte hain. Heatmap correlation ke
liye aur boxplot outlier detection ke liye interview mein poochhe jaate hain.
Aaj ka Practice:
1. Monthly sales line chart banao — grid aur markers ke saath
2. City-wise revenue bar chart — different colors
3. Department-wise pie chart
4. Kaggle dataset se histogram banao
5. Correlation heatmap banao — seaborn
Aaj kya seekha:
✓ Matplotlib se basic plots banana aaya
✓ Seaborn se statistical plots aaye
✓ Chart save karna aaya
✓ Heatmap aur boxplot samjha
Python 15-Day Notes | Page 35
DAY 15
Mini Project — EDA
Exploratory Data Analysis — Sab kuch ek saath
Project: Complete EDA on Sales Dataset
15 din mein jo seekha woh sab ek project mein use karo. EDA = Exploratory Data Analysis — nayi dataset
samajhne ka process.
Step 1: Setup aur Data Load
import pandas as pd
import numpy as np
import [Link] as plt
import seaborn as sns
# Data load karo (Kaggle se download karo)
df = pd.read_csv('sales_data.csv')
# Basic exploration
print('Shape:', [Link])
print('Columns:', [Link]())
print([Link]())
print([Link]())
print([Link]().sum())
Step 2: Data Cleaning
# Missing values handle karo
df['quantity'].fillna(df['quantity'].median(), inplace=True)
[Link](subset=['customer_id'], inplace=True)
# Duplicates hatao
df.drop_duplicates(inplace=True)
# Data types fix karo
df['order_date'] = pd.to_datetime(df['order_date'])
df['revenue'] = df['quantity'] * df['unit_price']
print('Cleaned shape:', [Link])
Step 3: Analysis
Python 15-Day Notes | Page 36
# KPIs
total_revenue = df['revenue'].sum()
total_orders = df['order_id'].nunique()
avg_order = df['revenue'].mean()
print(f"Total Revenue: Rs {total_revenue:,.0f}")
print(f"Total Orders: {total_orders}")
print(f"Avg Order Value: Rs {avg_order:,.0f}")
# City-wise analysis
city_rev = [Link]('city')['revenue'].sum().sort_values(ascending=False)
print(city_rev.head())
# Monthly trend
df['month'] = df['order_date'].dt.to_period('M')
monthly = [Link]('month')['revenue'].sum()
Step 4: Visualization Dashboard
fig, axes = [Link](2, 2, figsize=(15, 10))
[Link]('Sales Dashboard', fontsize=16, fontweight='bold')
# Plot 1: Monthly trend
[Link](ax=axes[0,0], kind='line', marker='o', color='blue')
axes[0,0].set_title('Monthly Revenue Trend')
# Plot 2: City-wise bar
city_rev.head(8).plot(ax=axes[0,1], kind='bar', color='teal')
axes[0,1].set_title('Top Cities by Revenue')
# Plot 3: Category pie
cat_rev = [Link]('category')['revenue'].sum()
cat_rev.plot(ax=axes[1,0], kind='pie', autopct='%1.1f%%')
axes[1,0].set_title('Category-wise Share')
# Plot 4: Revenue distribution
axes[1,1].hist(df['revenue'], bins=30, color='purple', alpha=0.7)
axes[1,1].set_title('Order Value Distribution')
plt.tight_layout()
[Link]('sales_dashboard.png', dpi=150)
[Link]()
print('Dashboard saved!')
Aaj ka Practice:
1. Kaggle pe 'sales dataset' search karo — download karo
2. Upar di gayi sab steps follow karo
3. 5 additional insights nikalo — apne aap se
4. Dashboard save karo — LinkedIn pe daalo
5. GitHub pe .ipynb file upload karo — portfolio!
Python 15-Day Notes | Page 37
Aaj kya seekha:
✓ 15 din ka Python course complete!
✓ EDA karna aata hai
✓ Complete data pipeline: load, clean, analyze, visualize
✓ Portfolio ke liye project ready!
Python 15-Day Notes | Page 38
Python Cheat Sheet — Quick Reference
Concept Code
Print print('Hello', name)
Input x = input('Enter: ')
Variables name = 'Ram'; age = 22
f-string f'Hello {name}, age {age}'
Type convert int('5'), str(5), float('3.14')
List create lst = [1, 2, 3, 4, 5]
List add [Link](6); [Link]([7,8])
List comprehension [x**2 for x in range(5)]
Dict create d = {'key': 'value'}
Dict access [Link]('key', 'default')
Dict loop for k,v in [Link]()
if/elif/else if x>0: ... elif x<0: ... else: ...
Ternary val = 'A' if x>90 else 'B'
for loop for i in range(10): ...
enumerate for i,v in enumerate(lst, 1)
zip for a,b in zip(lst1, lst2)
while while condition: ...
Function def func(a, b=10): return a+b
Lambda f = lambda x: x**2
*args def f(*args): sum(args)
**kwargs def f(**kw): [Link]()
try/except try: ... except Error as e: ...
File write with open('[Link]','w') as f: [Link](...)
File read with open('[Link]','r') as f: [Link]()
CSV read pd.read_csv('[Link]')
NumPy array [Link]([1,2,3])
np stats [Link](a), [Link](a), [Link](a)
Pandas load df = pd.read_csv('[Link]')
DF filter df[df['col'] > 100]
DF groupby [Link]('city')['sal'].mean()
DF new col df['new'] = df['a'] * df['b']
Plot line [Link](x, y); [Link]()
Plot bar [Link](x, y); [Link]()
Python 15-Day Notes | Page 39
Seaborn heat [Link]([Link](), annot=True)
Python 15-Day Notes | Page 40
Python seekh liya — Aage kya?
Excel + SQL + Python (Pandas) = Complete Data Analyst Toolkit! Ab Power BI seekho aur
job-ready ho jaao.
"Code likhna mat darao — har error ek nayi cheez sikhata hai. Bas likhte raho."
Python 15-Day Notes | Page 41