PYTHON MASTERCLASS NOTES
Basics to Pandas — Complete Reference for Freshers, Data Engineers, Analysts & Scientists
Prepared for: Sanjay | B.E. CSE (AI & ML)
Contents
● 1. Python Basics — Syntax, Variables, Data Types
● 2. Operators
● 3. Control Flow — if/elif/else, loops
● 4. Functions
● 5. Strings
● 6. Data Structures — List, Tuple, Set, Dictionary
● 7. Object-Oriented Programming (OOP)
● 8. Exception Handling
● 9. File Handling
● 10. Modules & Packages
● 11. Comprehensions & Lambda
● 12. Iterators, Generators, Decorators
● 13. NumPy Essentials
● 14. Pandas Essentials
● 15. Quick Interview Q&A
1. Python Basics
1.1 Syntax & Variables
Python-la variable declare panna type keyword venaam. Value assign panna automatic-ah type decide aagum
(Dynamic Typing).
x = 10 # int
name = "Sanjay" # str
price = 99.5 # float
is_active = True # bool
📌 Note: Python case-sensitive. Variable name numbers start aaga koodathu, keywords use pannakoodathu (e.g.
class, def).
1.2 Data Types
Type Example Description
int x=5 Whole numbers
float x = 5.5 Decimal numbers
str x = "hi" Text / string
bool x = True True / False
list x = [1,2,3] Ordered, mutable collection
tuple x = (1,2,3) Ordered, immutable
set x = {1,2,3} Unordered, unique elements
dict x = {"a":1} Key-value pairs
1.3 Type Conversion
int("10") # str -> int
str(10) # int -> str
float("3.14") # str -> float
list("abc") # -> ['a','b','c']
2. Operators
Category Operators Example
Arithmetic + - * / // % ** 7 // 2 = 3, 7 % 2 = 1
Comparison == != > < >= <= 5 == 5 -> True
Logical and or not True and False -> False
Assignment = += -= *= /= x += 1
Membership in , not in 'a' in 'cat' -> True
Identity is , is not a is b
📌 Note: // -> Floor division (result whole number), ** -> Power/Exponent.
3. Control Flow
3.1 if / elif / else
age = 20
if age < 13:
print("Child")
elif age < 20:
print("Teenager")
else:
print("Adult")
3.2 for loop
for i in range(5):
print(i) # 0 1 2 3 4
for fruit in ["apple", "mango"]:
print(fruit)
3.3 while loop
i = 0
while i < 5:
print(i)
i += 1
3.4 break, continue, pass
Keyword Purpose
break Loop-a immediate ah stop pannum
continue Current iteration skip panni next-ku pogum
pass Nothing operation — placeholder
4. Functions
def greet(name, msg="Hello"):
return f"{msg}, {name}!"
print(greet("Sanjay")) # Hello, Sanjay!
print(greet("Sanjay", "Hi")) # Hi, Sanjay!
4.1 Types of Arguments
Type Example
Positional greet('Sanjay')
Keyword greet(name='Sanjay')
Default def greet(name, msg='Hi')
*args def f(*args) -> variable positional args
**kwargs def f(**kwargs) -> variable keyword args
def total(*nums):
return sum(nums)
total(1,2,3) # 6
def info(**data):
for k,v in [Link]():
print(k, v)
info(name="Sanjay", age=20)
5. Strings
s = "Data Engineering"
[Link]() # DATA ENGINEERING
[Link]() # data engineering
[Link]() # ['Data','Engineering']
[Link]("Data","AI")
s[0:4] # slicing -> 'Data'
[Link]() # remove spaces
len(s) # length
f"Hi {s}" # f-string
📌 Note: String immutable — once create pannina change panna mudiyathu, but new string create pannalam.
6. Data Structures
6.1 List
fruits = ["apple", "mango", "banana"]
[Link]("grape")
[Link]("mango")
fruits[0] # 'apple'
[Link]()
len(fruits)
6.2 Tuple
t = (1, 2, 3)
t[0] # 1
# t[0] = 5 -> Error! Tuple immutable
6.3 Set
s = {1, 2, 3}
[Link](4)
[Link](2)
# Duplicate values automatic-ah remove aagum
6.4 Dictionary
student = {"name": "Sanjay", "year": 4}
student["name"] # 'Sanjay'
student["dept"] = "CSE-AIML"
[Link]()
[Link]()
[Link]()
6.5 Comparison Table
Structure Ordered Mutable Duplicates
List Yes Yes Allowed
Tuple Yes No Allowed
Set No Yes Not Allowed
Dict Yes (3.7+) Yes Keys unique
7. Object-Oriented Programming (OOP)
class Student:
def __init__(self, name, marks):
[Link] = name
[Link] = marks
def display(self):
print(f"{[Link]}: {[Link]}")
s1 = Student("Sanjay", 90)
[Link]()
7.1 OOP Pillars
Concept Meaning
Encapsulation Data & methods-a one unit-a wrap panradhu
Inheritance Oru class matha class oda properties eduthukaradhu
Polymorphism Same method, different classes-la different behaviour
Abstraction Implementation details hide panni essential features mattum expose
panradhu
7.2 Inheritance Example
class Animal:
def sound(self):
print("Some sound")
class Dog(Animal):
def sound(self):
print("Bark")
d = Dog()
[Link]() # Bark (overridden)
8. Exception Handling
try:
x = 10 / 0
except ZeroDivisionError as e:
print("Error:", e)
else:
print("No error")
finally:
print("Always runs")
Common Exception Cause
ZeroDivisionError Division by 0
ValueError Wrong value type
TypeError Operation on wrong type
IndexError Invalid index access
KeyError Dict key not found
FileNotFoundError File illa
9. File Handling
# Write
with open("[Link]", "w") as f:
[Link]("Hello Sanjay")
# Read
with open("[Link]", "r") as f:
content = [Link]()
print(content)
# Append
with open("[Link]", "a") as f:
[Link]("\nNew line")
Mode Meaning
r Read (default)
w Write (overwrites)
a Append
r+ Read & Write
📌 Note: 'with' statement use pannina file automatic-ah close aagum — best practice.
10. Modules & Packages
import math
[Link](16) # 4.0
from datetime import datetime
[Link]()
import numpy as np
import pandas as pd
Module = single .py file. Package = folder containing multiple modules with __init__.py.
11. Comprehensions & Lambda
11.1 List Comprehension
squares = [x**2 for x in range(5)]
# [0, 1, 4, 9, 16]
evens = [x for x in range(10) if x % 2 == 0]
11.2 Dict Comprehension
d = {x: x**2 for x in range(5)}
11.3 Lambda Function
add = lambda a, b: a + b
add(3, 4) # 7
nums = [1,2,3,4]
list(map(lambda x: x*2, nums))
list(filter(lambda x: x%2==0, nums))
12. Iterators, Generators, Decorators
12.1 Generator
def counter(limit):
n = 0
while n < limit:
yield n
n += 1
for val in counter(3):
print(val) # 0 1 2
📌 Note: Generator memory-la ella values-um store pannaadhu, oru time-ku oru value mattum produce pannum
(lazy evaluation) — periya datasets ku useful.
12.2 Decorator
def my_decorator(func):
def wrapper():
print("Before function")
func()
print("After function")
return wrapper
@my_decorator
def say_hello():
print("Hello")
say_hello()
13. NumPy Essentials
import numpy as np
arr = [Link]([1, 2, 3, 4])
[Link] # (4,)
[Link]
mat = [Link]([[1,2],[3,4]])
[Link] # (2,2)
[Link]((2,3))
[Link]((2,3))
[Link](0,10,2) # [0,2,4,6,8]
[Link](0,1,5)
arr + 2 # element-wise
arr * arr
[Link](arr)
[Link](arr)
[Link](arr) ; [Link](arr)
[Link](2,2)
13.1 Indexing & Slicing
arr[0] # first element
arr[1:3] # slice
mat[0,1] # row 0, col 1
mat[:,1] # entire column 1
📌 Note: NumPy array-la ella elements same data type-a irukanum, list-ah vida fast — vectorized operations.
14. Pandas Essentials
14.1 Series & DataFrame
import pandas as pd
s = [Link]([10,20,30])
data = {"name": ["Sanjay","Kumar"], "marks":[90,85]}
df = [Link](data)
[Link]()
[Link]
[Link]()
[Link]()
14.2 Reading Files
df = pd.read_csv("[Link]")
df = pd.read_excel("[Link]")
df.to_csv("[Link]", index=False)
14.3 Selecting Data
df["name"] # column
df[["name","marks"]] # multiple columns
[Link][0] # row by label
[Link][0] # row by position
df[df["marks"] > 85] # filter condition
14.4 Cleaning Data
[Link]().sum()
[Link]()
[Link](0)
[Link]()
df.drop_duplicates()
[Link](columns={"name":"student_name"})
14.5 GroupBy & Aggregation
[Link]("dept")["marks"].mean()
df.sort_values("marks", ascending=False)
df["marks"].apply(lambda x: x + 5)
14.6 Merging
[Link](df1, df2, on="id", how="inner")
# how: inner, left, right, outer
[Link]([df1, df2])
15. Quick Interview Q&A
Q1. List vs Tuple?
List mutable, Tuple immutable. List [], Tuple ().
Q2. is vs ==?
'==' value compare pannum, 'is' identity (memory location) compare pannum.
Q3. Mutable vs Immutable?
Mutable = change panna mudiyum (list, dict, set). Immutable = change panna mudiyathu (int, str, tuple).
Q4. Deep copy vs Shallow copy?
Shallow copy — reference mattum copy aagum (nested objects share aagum). Deep copy — completely
independent copy.
Q5. *args vs **kwargs?
*args -> variable number positional arguments (tuple). **kwargs -> variable number keyword arguments (dict).
Q6. Local vs Global variable?
Local — function-ku ulla mattum accessible. Global — entire program-la accessible.
Q7. What is PEP8?
Python code style guide — naming conventions, indentation rules.
Q8. What is GIL?
Global Interpreter Lock — oru time-ku oru thread mattum Python bytecode execute pannum.
Q9. List comprehension advantage?
Short, readable, and faster than normal for loop with append.
Q10. Pandas Series vs DataFrame?
Series = 1D labeled array. DataFrame = 2D table (multiple Series combined).