■
Zero to Advanced Python
A Complete Course — From Beginner to Expert
Python 3.12+ Zero to Advanced Hinglish Style Projects Included Interview Ready
Comprehensive Python Curriculum | Edition 2025
Table of Contents
Module 00 — Introduction to Python
• What is Python?
• Why Learn Python in 2025?
• Installation & Setup
• ■ Notes & Tips
• Practice Questions
Module 01 — Variables & Data Types
• What is a Variable?
• Core Data Types
• Type Conversion
• id(), Memory & Interning
• ■ Notes & Tips
• Practice Questions
Module 02 — Strings — Deep Dive
• String Basics & Creation
• Indexing & Slicing
• String Methods (Complete Reference)
• String Formatting (4 Ways)
• Advanced String Problems
• ■ Notes & Tips
• Practice Questions
Module 03 — Operators
• All Operator Types
• Operator Precedence (PEMDAS in Python)
• Practice Questions
Module 04 — Conditional Statements
• if / elif / else
• Practice Questions
Module 05 — Loops — for, while, Nested
• for Loop
• while Loop
• Loop Control: break, continue, pass
• Nested Loops & Patterns
• Practice Questions
Module 06 — Functions
• Defining & Calling Functions
• *args and **kwargs
• Scope: LEGB Rule
• Lambda Functions
• Recursion
• Practice Questions
Module 07 — Data Structures — List, Tuple, Set, Dictionary
• List — Ordered, Mutable, Allows Duplicates
• Tuple — Ordered, Immutable
• Set — Unordered, Unique, Mutable
• Dictionary — Key-Value Store (VERY DEEP)
• Practice Questions
Module 08 — File Handling
• Reading & Writing Files
• CSV, JSON, os Module
• Practice Questions
Module 09 — Exception Handling
• try / except / else / finally
• Custom Exceptions & Exception Hierarchy
• Practice Questions
Module 10 — Object-Oriented Programming — Complete Guide
• Class & Object Basics
• Inheritance (All Types)
• Encapsulation & Properties
• Polymorphism & Abstraction
• Magic / Dunder Methods
• Class Methods, Static Methods, Properties
• Practice Questions
Module 11 — Advanced Python Concepts
• List Comprehension (Deep)
• Generators & Iterators
• Decorators
• Context Managers
• Regex (Regular Expressions)
• Multithreading & Multiprocessing
• Practice Questions
Module 12 — Libraries — NumPy & Pandas
• NumPy Basics
• Pandas Basics
• Practice Questions
Module 13 — Real-World Mini Projects
• Project 1: Calculator (CLI)
• Project 2: Password Generator
• Project 3: File Organizer
• Project 4: CLI Todo App
Module 14 — Revision Cheatsheet & Top Interview Questions
• Python Cheatsheet — Quick Reference
• Top 30 Python Interview Questions
• Project Ideas for Your Portfolio
Zero to Advanced Python Course Page 3
MODULE
00 Introduction to Python
What is Python?
Python ek high-level, interpreted, general-purpose programming language hai jo 1991 mein Guido van
Rossum ne banai thi. Iska naam Monty Python comedy group se liya gaya hai.
Python ka design philosophy — code ko readable aur simple banana — is baat ko English jaise likhne deta
hai. Yahi reason hai ki Python beginners ke liye best first language hai, aur professionals ke liye bhi
top choice.
Key properties:
• Interpreted — code line by line execute hoti hai, compile nahi hoti
• Dynamically typed — variable ka type runtime par decide hota hai
• Garbage collected — memory automatically manage hoti hai
• Multi-paradigm — OOP, functional, procedural sab support karta hai
• Cross-platform — Windows, Mac, Linux sab par run hota hai
Why Learn Python in 2025?
Python aaj duniya ki #1 most-popular language hai (TIOBE Index, Stack Overflow Survey 2024).
Use cases:
• Web Development — Django, Flask, FastAPI
• Data Science & ML — NumPy, Pandas, TensorFlow, PyTorch
• Automation & Scripting — selenium, pyautogui
• Cybersecurity — penetration testing tools
• Finance & Quant — algorithmic trading
• DevOps & Cloud — AWS Lambda, Docker scripts
• Game Development — Pygame
Zero to Advanced Python Course Page 4
Salary range (India 2025): ■4 LPA (fresher) → ■40+ LPA (senior)
Salary range (USA 2025): $70k (junior) → $200k+ (senior/ML engineer)
Installation & Setup
Step 1 — Download Python:
Visit [Link] aur latest version (3.12+) download karo.
Windows pe installer run karo — 'Add Python to PATH' checkbox zaroor tick karo!
Step 2 — Verify Installation:
Terminal/Command Prompt mein type karo:
python --version
Output: Python 3.12.x
Step 3 — Install VS Code (Recommended IDE):
[Link] se download karo
Extension install karo: 'Python' by Microsoft
Step 4 — Virtual Environment (Best Practice):
python -m venv myenv
Windows: myenv\Scripts\activate
Mac/Linux: source myenv/bin/activate
Step 5 — Your First Program:
print('Hello, World!')
Save as [Link] → run: python [Link]
■ Notes & Tips
■ Python 2 vs Python 3: Always use Python 3. Python 2 is dead (EOL 2020).
Zero to Advanced Python Course Page 5
■ REPL: Type 'python' in terminal to open interactive shell — great for quick experiments.
■■ Common Mistake: Not adding Python to PATH on Windows. If 'python' command not found, reinstall and check
the 'Add to PATH' checkbox.
■ Interview Insight: Python is interpreted AND compiled — .py files compile to .pyc (bytecode) first, then the Python
VM interprets that bytecode.
Practice Questions
1. What does 'interpreted language' mean? 2. Difference between Python 2 and Python 3? 3. What is a virtual
environment and why use it? 4. Name 5 real-world applications of Python. 5. What does PEP 8 stand for? Coding
Challenges: C1. Write a program that prints your name, age, and city. C2. Use the print() function to display a
formatted receipt for a grocery bill.
Zero to Advanced Python Course Page 6
MODULE
01 Variables & Data Types
What is a Variable?
Variable ek container hai jo data store karta hai. Python mein variable declare karne ke liye koi
keyword (jaise 'int', 'var') use nahi hota — simply naam likho aur value assign karo.
Rules for variable names:
• Letter ya underscore se start hona chahiye
• Digits (0-9) bhi use kar sakte ho, but start mein nahi
• Case-sensitive: 'age' aur 'Age' alag variables hain
• Reserved keywords use nahi kar sakte (if, for, class, etc.)
Code Examples:
name = 'Rahul' # string
age = 25 # integer
salary = 45000.50 # float
is_employed = True # boolean
data = None # NoneType
Multiple assignment:
x, y, z = 1, 2, 3 # unpack
a = b = c = 0 # all same value
type() function:
print(type(age)) # <class 'int'>
print(type(name)) # <class 'str'>
Core Data Types
Zero to Advanced Python Course Page 7
Python mein built-in data types:
1. int — integers (whole numbers)
x = 100
big = 10_000_000 # underscore for readability
binary = 0b1010 # binary = 10
hexa = 0xFF # hex = 255
2. float — decimal numbers (IEEE 754 double precision)
pi = 3.14159
sci = 1.5e-3 # scientific notation = 0.0015
import sys; print(sys.float_info.max) # max float
3. complex — complex numbers
c = 3 + 4j
print([Link], [Link]) # 3.0 4.0
4. str — strings (immutable sequence of characters)
s = 'Hello'
s2 = "World"
s3 = '''Multi
line'''
5. bool — True or False (subclass of int!)
print(True + True) # 2
print(bool(0)) # False
print(bool('')) # False
6. NoneType — represents absence of value
Zero to Advanced Python Course Page 8
result = None
print(result is None) # True
Type Conversion
Type conversion — ek type se doosre mein convert karna.
Implicit (Python auto-converts):
x = 5 + 2.0 # int + float = float (3.0)
Explicit (aap manually convert karo):
int('42') # → 42
float('3.14') # → 3.14
str(100) # → '100'
bool(0) # → False
list('abc') # → ['a', 'b', 'c']
Real example:
age_str = input('Enter age: ') # input() always returns str
age_int = int(age_str) # convert to int
print('Next year you will be', age_int + 1)
■■ int('3.14') raises ValueError — convert float string to float first:
int(float('3.14')) # → 3
id(), Memory & Interning
id() returns the memory address of an object.
a = 5
Zero to Advanced Python Course Page 9
b = 5
print(id(a) == id(b)) # True — Python interns small ints (-5 to 256)
x = 1000
y = 1000
print(id(x) == id(y)) # False — large ints are NOT interned
String interning:
s1 = 'hello'
s2 = 'hello'
print(s1 is s2) # Usually True — Python interns short strings
s3 = 'hello world'
s4 = 'hello world'
print(s3 is s4) # May be False for longer strings
■ Interview Insight: 'is' checks identity (same object), '==' checks equality (same value). Never use
'is' to compare values — always use '==' for value comparison.
■ Notes & Tips
■ Python variables are labels pointing to objects, not boxes storing values.
■ Use snake_case for variable names (PEP 8 convention): my_variable, total_price.
■■ Common Mistake: Confusing '=' (assignment) with '==' (comparison).
■■ Avoid naming variables after built-ins: list, dict, str, type, id, etc.
■ Interview Q: What are mutable vs immutable types? Immutable: int, float, str, tuple, frozenset, bool Mutable: list,
dict, set, user-defined classes
Practice Questions
Zero to Advanced Python Course Page 10
1. What will print(type(True)) output? 2. What is the output of: print(10 / 3) vs print(10 // 3)? 3. Can a variable name
start with a number? Why/why not? 4. What is None and how is it different from 0 or ''? 5. What is type coercion
(implicit conversion)? Give an example. 6. What is the difference between is and == operators? 7. Can you store
different types in the same variable at different times? Coding Challenges: C1. Take user's name and birth year as
input, calculate and print their age. C2. Create variables for a product (name, price, quantity), calculate total bill with
18% GST and print a formatted bill.
Zero to Advanced Python Course Page 11
MODULE
02 Strings — Deep Dive
String Basics & Creation
String ek immutable sequence of Unicode characters hai.
Creating strings:
s1 = 'single quotes'
s2 = "double quotes"
s3 = '''triple single — multi-line
string here'''
s4 = """triple double — also multi-line"""
Special strings:
raw = r'C:\Users\name' # raw string — backslash treated literally
byte = b'hello' # bytes object
Escape sequences:
'\n' = newline, '\t' = tab, '\\' = backslash
'\'' = quote, '\r' = carriage return
String repetition & concatenation:
'ha' * 3 # 'hahaha'
'Hello' + ' World' # 'Hello World'
len():
len('Python') # 6
Indexing & Slicing
Zero to Advanced Python Course Page 12
String indexing — 0 se start hoti hai. Negative indexing bhi possible hai!
s = 'P Y T H O N'
0 1 2 3 4 5
-6-5-4-3-2-1
s[0] # 'P'
s[-1] # 'N'
s[-2] # 'O'
Slicing syntax: s[start:stop:step]
s = 'PYTHON'
s[0:3] # 'PYT' (0,1,2 — stop is excluded)
s[2:] # 'THON' (2 to end)
s[:4] # 'PYTH' (start to 4)
s[::2] # 'PTO' (every 2nd character)
s[::-1] # 'NOHTYP' (reversed!)
s[1:5:2] # 'YH'
Advanced examples:
s = 'Hello World'
s[6:] # 'World'
s[:5] # 'Hello'
s[-5:] # 'World'
s[::1] # 'Hello World' (copy)
s[::-1] # 'dlroW olleH'
Check substring:
Zero to Advanced Python Course Page 13
'ell' in 'Hello' # True
'xyz' not in 'Hello' # True
String Methods (Complete Reference)
CASE METHODS:
s = 'hello world'
[Link]() # 'HELLO WORLD'
[Link]() # 'hello world'
[Link]() # 'Hello World'
[Link]() # 'Hello world'
[Link]() # 'HELLO WORLD' → 'hello world'
SEARCH METHODS:
s = 'Python is great'
[Link]('is') # 7 (index) or -1 if not found
[Link]('is') # 7 (raises ValueError if not found)
[Link]('t') # 2
[Link]('Py') # True
[Link]('t') # True
STRIP METHODS:
s = ' hello '
[Link]() # 'hello' (remove both sides)
[Link]() # 'hello ' (left only)
[Link]() # ' hello' (right only)
'xxhelloxx'.strip('x') # 'hello'
Zero to Advanced Python Course Page 14
SPLIT & JOIN:
'a,b,c'.split(',') # ['a','b','c']
'hello world'.split() # ['hello','world'] (whitespace)
'a,b,c'.split(',', 1) # ['a','b,c'] (maxsplit)
'-'.join(['a','b','c']) # 'a-b-c'
''.join(['H','i']) # 'Hi'
REPLACE & FORMAT:
'hello'.replace('l','r') # 'herro'
'hello'.replace('l','r',1) # 'herlo' (max 1 replace)
'5'.zfill(3) # '005' (zero-fill)
'hi'.center(10, '-') # '----hi----'
'hi'.ljust(10, '.') # 'hi........'
'hi'.rjust(10, '.') # '........hi'
VALIDATION METHODS:
'abc'.isalpha() # True (only letters)
'123'.isdigit() # True (only digits)
'abc123'.isalnum() # True (letters + digits)
' '.isspace() # True (only whitespace)
'HELLO'.isupper() # True
'hello'.islower() # True
'Hello World'.istitle() # True
ENCODING:
'hello'.encode('utf-8') # b'hello'
b'hello'.decode('utf-8') # 'hello'
Zero to Advanced Python Course Page 15
String Formatting (4 Ways)
WAY 1 — % formatting (old style, avoid in new code):
name = 'Rahul'; age = 25
print('Name: %s, Age: %d' % (name, age))
# Name: Rahul, Age: 25
WAY 2 — [Link]() (Python 3+):
print('Name: {}, Age: {}'.format(name, age))
print('Name: {0}, Age: {1}'.format(name, age)) # positional
print('Name: {n}, Age: {a}'.format(n=name, a=age)) # keyword
WAY 3 — f-strings (Python 3.6+, RECOMMENDED):
print(f'Name: {name}, Age: {age}')
print(f'Next year: {age + 1}') # expressions work!
pi = 3.14159
print(f'Pi = {pi:.2f}') # Pi = 3.14
print(f'{name!r}') # repr: 'Rahul'
print(f'{name!u}') # uppercase
num = 1000000
print(f'{num:,}') # 1,000,000
print(f'{0.5:.1%}') # 50.0%
print(f'{42:08b}') # 00101010 (binary)
print(f'{"hello":^20}') # centered in 20 chars
WAY 4 — Template strings (rare, for user-supplied templates):
from string import Template
t = Template('Hello, $name!')
Zero to Advanced Python Course Page 16
print([Link](name='World')) # Hello, World!
Python 3.12 f-string improvements:
# Nested quotes and multi-line now supported
print(f"Result: {', '.join(['a','b','c'])}")
Advanced String Problems
PROBLEM 1 — Palindrome check:
def is_palindrome(s):
s = [Link]().replace(' ', '')
return s == s[::-1]
print(is_palindrome('Racecar')) # True
PROBLEM 2 — Count vowels:
def count_vowels(s):
return sum(1 for c in [Link]() if c in 'aeiou')
print(count_vowels('Hello World')) # 3
PROBLEM 3 — Anagram check:
def is_anagram(a, b):
return sorted([Link]()) == sorted([Link]())
print(is_anagram('listen', 'silent')) # True
PROBLEM 4 — Compress string:
def compress(s):
result = ''
count = 1
for i in range(1, len(s)):
Zero to Advanced Python Course Page 17
if s[i] == s[i-1]:
count += 1
else:
result += s[i-1] + (str(count) if count > 1 else '')
count = 1
result += s[-1] + (str(count) if count > 1 else '')
return result
print(compress('aaabbc')) # 'a3b2c'
PROBLEM 5 — Caesar cipher:
def caesar(text, shift):
result = ''
for char in text:
if [Link]():
base = ord('A') if [Link]() else ord('a')
result += chr((ord(char) - base + shift) % 26 + base)
else:
result += char
return result
print(caesar('Hello', 3)) # 'Khoor'
■ Notes & Tips
■ Strings are immutable — you can't change a character in place. Create new strings.
■ Use f-strings for all new code — fastest and most readable.
■ [Link]() is faster than + for concatenating many strings in a loop.
■■ Common Mistake: Forgetting that split() without argument splits on ANY whitespace and removes empty strings.
Zero to Advanced Python Course Page 18
■ Interview: How to reverse a string? → s[::-1]
■ Interview: Difference between find() and index()? → find() returns -1 on failure, index() raises ValueError.
■ Strings in Python store Unicode — emoji, Hindi, Chinese all work natively.
Practice Questions
1. What is the output of 'Python'[1::2]? 2. How do you check if a string contains only digits? 3. What does strip('xyz')
do vs strip()? 4. How do you format a float to 2 decimal places using f-strings? 5. What is the difference between
encode() and decode()? 6. How many times does 'l' appear in 'Hello World'? 7. Write a one-liner to reverse every
word in a sentence. Coding Challenges: C1. Write a function that checks if a string is a pangram (contains every
letter of the alphabet). C2. Write a program that takes a sentence and capitalizes the first letter of each word without
using title() or capitalize().
Zero to Advanced Python Course Page 19
MODULE
03 Operators
All Operator Types
ARITHMETIC OPERATORS:
+ Addition: 5 + 3 = 8
- Subtraction: 5 - 3 = 2
* Multiplication: 5 * 3 = 15
/ Division: 7 / 2 = 3.5 (always float)
// Floor Division: 7 // 2 = 3 (rounds down)
% Modulus: 7 % 2 = 1 (remainder)
** Exponent: 2 ** 10 = 1024
COMPARISON OPERATORS (return bool):
== Equal: 5 == 5 → True
!= Not Equal: 5 != 3 → True
> Greater: 5 > 3 → True
< Less: 3 < 5 → True
>= Greater/Equal: 5 >= 5 → True
<= Less/Equal: 3 <= 5 → True
# Chaining: 1 < x < 10 works in Python!
ASSIGNMENT OPERATORS:
= x = 5
+= x += 3 (x = x + 3)
-= x -= 3
*= x *= 2
Zero to Advanced Python Course Page 20
/= x /= 2
//= x //= 2
%= x %= 3
**= x **= 2
:= walrus operator (Python 3.8+): assigns in expression
while (n := int(input())) != 0:
print(n)
LOGICAL OPERATORS:
and → True if both True
or → True if at least one True
not → inverts the bool
Short-circuit: 'and' stops at first False, 'or' stops at first True
print(0 or 'hello') # 'hello' ← or returns first truthy value
print(5 and 'hi') # 'hi' ← and returns last truthy value
BITWISE OPERATORS:
& AND: 5 & 3 = 1 (0101 & 0011 = 0001)
| OR: 5 | 3 = 7 (0101 | 0011 = 0111)
^ XOR: 5 ^ 3 = 6 (0101 ^ 0011 = 0110)
~ NOT: ~5 = -6
<< Left shift: 5 << 1 = 10 (multiply by 2)
>> Right shift: 5 >> 1 = 2 (divide by 2)
IDENTITY & MEMBERSHIP:
is, is not → check if same object in memory
in, not in → check membership in sequence
Zero to Advanced Python Course Page 21
3 in [1,2,3] # True
'a' not in 'hello' # True
Operator Precedence (PEMDAS in Python)
Highest to Lowest:
1. () Parentheses
2. ** Exponentiation (right-to-left!)
3. +x, -x, ~x Unary
4. *, /, //, % Multiply/Divide
5. +, - Add/Subtract
6. <<, >> Bitwise shifts
7. & Bitwise AND
8. ^ Bitwise XOR
9. | Bitwise OR
10. ==, !=, <, >, <=, >=, is, is not, in, not in
11. not
12. and
13. or
Examples:
2 + 3 * 4 # 14 (not 20 — * before +)
(2 + 3) * 4 # 20
2 ** 3 ** 2 # 512 (= 2**9, right-to-left: 3**2=9, then 2**9)
not True or True # True (not before or)
Practice Questions
Zero to Advanced Python Course Page 22
1. What is the difference between / and //? 2. What does 10 % 3 return and what is it used for? 3. Explain short-circuit
evaluation with an example. 4. What is the walrus operator (:=) and when to use it? 5. What is the result of 3 < 5 < 10
in Python? Coding Challenges: C1. Write a program to check if a number is odd or even using the % operator. C2.
Using bitwise operators, write a function that checks if a number is a power of 2.
Zero to Advanced Python Course Page 23
MODULE
04 Conditional Statements
if / elif / else
Python mein indentation (whitespace) critical hai — blocks define karta hai.
Basic if:
age = 18
if age >= 18:
print('You can vote!')
if-else:
if age >= 18:
print('Adult')
else:
print('Minor')
if-elif-else:
score = 75
if score >= 90:
grade = 'A'
elif score >= 80:
grade = 'B'
elif score >= 70:
grade = 'C'
elif score >= 60:
grade = 'D'
else:
Zero to Advanced Python Course Page 24
grade = 'F'
print(f'Grade: {grade}') # Grade: C
Ternary (one-liner if-else):
status = 'Adult' if age >= 18 else 'Minor'
Nested if:
x = 15
if x > 0:
if x % 2 == 0:
print('Positive even')
else:
print('Positive odd')
else:
print('Non-positive')
Truthiness — falsy values in Python:
False, 0, 0.0, '', [], {}, (), set(), None
# Everything else is truthy!
if []: print('list') # won't print
if [0]: print('list') # WILL print — non-empty list is truthy
match statement (Python 3.10+ — structural pattern matching):
command = 'quit'
match command:
case 'quit':
print('Quitting...')
case 'help':
Zero to Advanced Python Course Page 25
print('Showing help...')
case _:
print('Unknown command')
Practice Questions
1. What are falsy values in Python? List all of them. 2. Can you have an if without an else? An elif without an if? 3.
What is a ternary expression? Write one. 4. What is the match statement introduced in Python 3.10? 5. Explain the
difference between 'if x:' and 'if x is not None:'. Coding Challenges: C1. FizzBuzz: Print numbers 1-100. For multiples
of 3 print 'Fizz', for multiples of 5 print 'Buzz', for multiples of both print 'FizzBuzz'. C2. Build a simple BMI calculator
that categorizes the result as Underweight/Normal/Overweight/Obese.
Zero to Advanced Python Course Page 26
MODULE
05 Loops — for, while, Nested
for Loop
for loop sequence/iterable ke har element par iterate karta hai.
Basic for:
for i in range(5):
print(i) # 0 1 2 3 4
range() function:
range(stop) # 0 to stop-1
range(start, stop) # start to stop-1
range(start, stop, step)
range(0, 10, 2) # 0,2,4,6,8
range(10, 0, -1) # 10,9,8,...,1 (countdown)
Iterating over sequences:
fruits = ['apple', 'banana', 'cherry']
for fruit in fruits:
print(fruit)
enumerate() — index + value:
for i, fruit in enumerate(fruits):
print(f'{i}: {fruit}')
# 0: apple, 1: banana, 2: cherry
zip() — iterate multiple lists together:
names = ['Alice', 'Bob']
Zero to Advanced Python Course Page 27
scores = [90, 85]
for name, score in zip(names, scores):
print(f'{name}: {score}')
for on string, dict, set:
for char in 'hello': print(char)
d = {'a': 1, 'b': 2}
for key in d: # iterates keys
for key, val in [Link](): # key-value pairs
while Loop
while loop tab tak chalta hai jab tak condition True ho.
Basic while:
count = 0
while count < 5:
print(count)
count += 1
while with break:
while True: # infinite loop
user = input('Enter q to quit: ')
if user == 'q':
break
print(f'You said: {user}')
while with else:
n = 5
Zero to Advanced Python Course Page 28
while n > 0:
print(n)
n -= 1
else:
print('Countdown done!') # runs after loop finishes normally
Loop Control: break, continue, pass
break — loop se bahar nikal jao:
for i in range(10):
if i == 5:
break
print(i) # prints 0,1,2,3,4
continue — current iteration skip karo:
for i in range(10):
if i % 2 == 0:
continue
print(i) # prints 1,3,5,7,9
pass — placeholder (do nothing):
for i in range(5):
pass # empty loop — no error
for...else / while...else:
The else block runs only if loop completed WITHOUT a break.
for i in range(5):
if i == 10: # never true
Zero to Advanced Python Course Page 29
break
else:
print('No break occurred') # This prints!
Use case — search and else:
numbers = [1, 3, 5, 7]
target = 4
for n in numbers:
if n == target:
print('Found!')
break
else:
print('Not found') # prints if target not in list
Nested Loops & Patterns
Nested loops (loop inside loop):
for i in range(3):
for j in range(3):
print(f'({i},{j})', end=' ')
print()
Pattern 1 — Right triangle:
for i in range(1, 6):
print('*' * i)
# *
# **
# ***
Zero to Advanced Python Course Page 30
# ****
# *****
Pattern 2 — Pyramid:
n = 5
for i in range(1, n+1):
print(' '*(n-i) + '*'*(2*i-1))
Multiplication table:
for i in range(1, 11):
for j in range(1, 11):
print(f'{i*j:4}', end='')
print()
Practice Questions
1. What is the difference between break and continue? 2. When does the else block of a for loop execute? 3. How
does enumerate() differ from range(len(list))? 4. How to loop over a dictionary's keys and values simultaneously? 5.
What is an infinite loop? How to safely create one? Coding Challenges: C1. Print all prime numbers between 1 and
100. C2. Write a program that finds the sum of digits of any number using a while loop.
Zero to Advanced Python Course Page 31
MODULE
06 Functions
Defining & Calling Functions
Function ek reusable block of code hai. DRY principle: Don't Repeat Yourself.
def keyword se define karo:
def greet(name):
'''Docstring: greet a person by name.'''
return f'Hello, {name}!'
print(greet('Rahul')) # Hello, Rahul!
Return values:
def add(a, b):
return a + b
# Multiple return values (actually a tuple):
def min_max(lst):
return min(lst), max(lst)
lo, hi = min_max([3, 1, 4, 1, 5]) # unpacking
Default parameters:
def power(base, exp=2):
return base ** exp
power(3) # 9 (exp defaults to 2)
power(3, 3) # 27
Zero to Advanced Python Course Page 32
■■ Mutable default argument trap:
def bad(lst=[]): # WRONG — list shared across calls!
[Link](1)
return lst
bad() # [1]
bad() # [1, 1] — unexpected!
def good(lst=None): # CORRECT
if lst is None:
lst = []
[Link](1)
return lst
*args and **kwargs
*args — variable number of positional arguments (tuple):
def total(*args):
return sum(args)
print(total(1, 2, 3, 4)) # 10
**kwargs — variable number of keyword arguments (dict):
def display(**kwargs):
for key, val in [Link]():
print(f'{key} = {val}')
display(name='Rahul', age=25, city='Delhi')
Both together:
def everything(a, b, *args, **kwargs):
Zero to Advanced Python Course Page 33
print(a, b, args, kwargs)
everything(1, 2, 3, 4, x=5, y=6)
# 1 2 (3, 4) {'x': 5, 'y': 6}
Unpacking with * and **:
nums = [1, 2, 3]
print(*nums) # 1 2 3 (unpacks list)
d = {'sep': '-'}
print(*nums, **d) # 1-2-3
Scope: LEGB Rule
Python looks up names in this order:
L — Local: Inside current function
E — Enclosing: Outer function (closures)
G — Global: Module level
B — Built-in: Python built-ins (len, print, etc.)
x = 'global'
def outer():
x = 'enclosing'
def inner():
x = 'local'
print(x) # 'local'
inner()
print(x) # 'enclosing'
outer()
print(x) # 'global'
Zero to Advanced Python Course Page 34
global keyword:
count = 0
def increment():
global count
count += 1
nonlocal keyword (closures):
def outer():
x = 0
def inner():
nonlocal x
x += 1
inner()
return x # 1
Lambda Functions
Lambda — anonymous one-liner function.
Syntax: lambda args: expression
square = lambda x: x ** 2
print(square(5)) # 25
add = lambda a, b: a + b
print(add(3, 4)) # 7
Common use — with sorted(), filter(), map():
students = [('Alice', 90), ('Bob', 75), ('Charlie', 85)]
Zero to Advanced Python Course Page 35
[Link](key=lambda s: s[1], reverse=True)
# [('Alice',90), ('Charlie',85), ('Bob',75)]
nums = [1, 2, 3, 4, 5, 6]
evens = list(filter(lambda x: x % 2 == 0, nums))
# [2, 4, 6]
squares = list(map(lambda x: x**2, nums))
# [1, 4, 9, 16, 25, 36]
from functools import reduce:
from functools import reduce
product = reduce(lambda x, y: x * y, [1,2,3,4,5])
# 120
Recursion
Recursion — function apne aap ko call karta hai.
Every recursion needs:
1. Base case (stopping condition)
2. Recursive case (reducing towards base)
Factorial:
def factorial(n):
if n <= 1: # base case
return 1
return n * factorial(n - 1) # recursive
print(factorial(5)) # 120
Zero to Advanced Python Course Page 36
Fibonacci:
def fib(n):
if n <= 1:
return n
return fib(n-1) + fib(n-2)
# Slow — O(2^n). Use memoization!
Memoized Fibonacci:
from functools import lru_cache
@lru_cache(maxsize=None)
def fib(n):
if n <= 1:
return n
return fib(n-1) + fib(n-2)
print(fib(100)) # Fast!
Binary search (recursive):
def binary_search(arr, target, lo, hi):
if lo > hi:
return -1
mid = (lo + hi) // 2
if arr[mid] == target:
return mid
elif arr[mid] < target:
return binary_search(arr, target, mid+1, hi)
else:
return binary_search(arr, target, lo, mid-1)
Zero to Advanced Python Course Page 37
■■ Python default recursion limit: 1000
import sys; [Link](10000)
Practice Questions
1. What is the difference between *args and **kwargs? 2. Explain the LEGB scope rule. 3. What is a closure? Write
an example. 4. Why should you avoid mutable default arguments? 5. What is a lambda function? When should you
NOT use it? 6. What is the recursion limit in Python and how to change it? 7. Difference between map(), filter(), and
reduce()? Coding Challenges: C1. Write a recursive function to compute the sum of all digits of a number. C2. Write a
function that returns a closure — a counter that tracks how many times it's called.
Zero to Advanced Python Course Page 38
MODULE Data Structures — List, Tuple, Set,
07
Dictionary
List — Ordered, Mutable, Allows Duplicates
List creation:
lst = [1, 2, 3, 4, 5]
mixed = [1, 'hello', 3.14, True, None]
nested = [[1,2],[3,4],[5,6]]
empty = []
from_range = list(range(10))
Accessing & Slicing:
lst[0] # first element
lst[-1] # last element
lst[1:4] # elements 1,2,3
lst[::-1] # reversed
List Methods:
[Link](6) # add to end
[Link](0, 0) # insert at index
[Link]([7, 8]) # add multiple
[Link](3) # remove first occurrence
[Link]() # remove & return last
[Link](0) # remove & return at index
[Link](4) # find index of value
[Link](2) # count occurrences
Zero to Advanced Python Course Page 39
[Link]() # sort in place (ascending)
[Link](reverse=True) # sort descending
[Link](key=len) # sort by custom key
sorted(lst) # returns new sorted list
[Link]() # reverse in place
[Link]() # shallow copy
[Link]() # remove all elements
List comprehension (see Module 11):
squares = [x**2 for x in range(10)]
Shallow vs Deep copy:
import copy
a = [[1,2],[3,4]]
b = [Link]() # shallow — nested lists still shared
c = [Link](a) # deep — completely independent
Tuple — Ordered, Immutable
Tuple — list jaisa but immutable (change nahi kar sakte).
Creation:
t = (1, 2, 3)
single = (42,) # comma required for single-element tuple!
packed = 1, 2, 3 # parentheses optional
Tuple unpacking:
a, b, c = (1, 2, 3)
first, *rest = (1, 2, 3, 4, 5)
Zero to Advanced Python Course Page 40
# first=1, rest=[2,3,4,5]
Swap variables using tuple:
a, b = b, a # Python magic!
Named Tuples:
from collections import namedtuple
Point = namedtuple('Point', ['x', 'y'])
p = Point(3, 4)
print(p.x, p.y) # 3 4
print(p[0], p[1]) # 3 4 — index also works
Why use tuples?
• Faster than lists
• Can be used as dict keys (immutable = hashable)
• Protect data from accidental modification
• Used for multiple return values from functions
Set — Unordered, Unique, Mutable
Set — mathematical set. No duplicates, no ordering.
Creation:
s = {1, 2, 3, 4, 5}
s = set([1, 2, 2, 3]) # {1, 2, 3} — duplicates removed
empty = set() # NOT {} — that's an empty dict!
Set operations:
a = {1, 2, 3, 4}
Zero to Advanced Python Course Page 41
b = {3, 4, 5, 6}
a | b # Union: {1,2,3,4,5,6}
a & b # Intersection: {3,4}
a - b # Difference: {1,2}
b - a # Difference: {5,6}
a ^ b # Symmetric difference: {1,2,5,6}
Methods:
[Link](6) # add element
[Link](3) # remove (no error if missing)
[Link](3) # remove (raises KeyError if missing)
[Link]() # remove random element
[Link]() # empty the set
[Link](t) # True if s ⊆ t
[Link](t) # True if s ⊇ t
[Link](t) # True if no common elements
frozenset — immutable set (can be used as dict key):
fs = frozenset([1, 2, 3])
Best use case — fast membership testing:
O(1) vs list O(n):
valid = {'admin', 'user', 'guest'}
if role in valid: # O(1) lookup!
Dictionary — Key-Value Store (VERY DEEP)
Dict — hash table implementation. Keys must be hashable (immutable).
Zero to Advanced Python Course Page 42
Creation:
d = {'name': 'Rahul', 'age': 25}
d = dict(name='Rahul', age=25)
d = dict([('a', 1), ('b', 2)]) # from list of tuples
keys = ['a','b','c']; vals = [1,2,3]
d = dict(zip(keys, vals)) # {'a':1,'b':2,'c':3}
Access & Modification:
d['name'] # 'Rahul' (KeyError if missing)
[Link]('name') # 'Rahul' (None if missing — safe!)
[Link]('x', 'N/A') # 'N/A' (default value)
d['age'] = 26 # update
d['city'] = 'Delhi' # add new key
del d['age'] # delete key
Dict Methods:
[Link]() # dict_keys — view of keys
[Link]() # dict_values — view of values
[Link]() # dict_items — (key,val) tuples
[Link]({'x': 1, 'y': 2}) # merge
[Link]('key') # remove and return value
[Link]() # remove last inserted (3.7+)
[Link]('z', 0) # set key if not exists
[Link]() # shallow copy
[Link]() # empty dict
Dict comprehension:
Zero to Advanced Python Course Page 43
squares = {x: x**2 for x in range(6)}
# {0:0, 1:1, 2:4, 3:9, 4:16, 5:25}
Merging dicts (Python 3.9+):
a = {'x': 1}; b = {'y': 2}
c = a | b # {'x':1, 'y':2}
a |= b # update a in place
Nested dicts:
students = {
'Alice': {'age': 20, 'grade': 'A'},
'Bob': {'age': 22, 'grade': 'B'},
print(students['Alice']['grade']) # 'A'
defaultdict (never KeyError):
from collections import defaultdict
word_count = defaultdict(int)
for word in 'hello world hello'.split():
word_count[word] += 1
# defaultdict(int, {'hello': 2, 'world': 1})
Counter:
from collections import Counter
c = Counter('banana')
# Counter({'a': 3, 'n': 2, 'b': 1})
c.most_common(2) # [('a',3), ('n',2)]
Zero to Advanced Python Course Page 44
OrderedDict:
from collections import OrderedDict
od = OrderedDict()
# Maintains insertion order (all dicts do in Python 3.7+)
Practice Questions
1. List vs Tuple — when to use which? 2. Why can't you use a list as a dictionary key? 3. How does set handle
duplicate values? 4. What is the time complexity of dict lookup, list search, and set search? 5. Explain defaultdict with
a practical example. 6. What is a shallow copy vs deep copy of a list? 7. How do you sort a dictionary by its values?
8. What does [Link]() do? Coding Challenges: C1. Given a list of words, find the most frequent word using a
dictionary. C2. Given two lists, write a function that returns their intersection, union, and difference.
Zero to Advanced Python Course Page 45
MODULE
08 File Handling
Reading & Writing Files
File modes:
'r' read (default) — file must exist
'w' write — creates/overwrites file
'a' append — adds to end of file
'x' exclusive create — fails if file exists
'rb' read binary
'wb' write binary
'r+' read and write
Reading:
with open('[Link]', 'r') as f:
content = [Link]() # entire file as string
lines = [Link]() # list of lines (with \n)
line = [Link]() # one line at a time
# Iterate line by line (memory-efficient):
with open('[Link]') as f:
for line in f:
print([Link]())
Writing:
with open('[Link]', 'w') as f:
[Link]('Hello World\n')
[Link](['Line1\n', 'Line2\n'])
Zero to Advanced Python Course Page 46
Appending:
with open('[Link]', 'a') as f:
[Link]('New log entry\n')
Always use 'with' statement — auto-closes file even if error occurs!
Working with paths (pathlib — modern way):
from pathlib import Path
p = Path('data/[Link]')
p.read_text() # read file
p.write_text('Hello') # write file
[Link]() # check existence
[Link] # '.txt'
[Link] # 'file'
[Link] # Path('data')
CSV, JSON, os Module
CSV files:
import csv
# Write:
with open('[Link]', 'w', newline='') as f:
writer = [Link](f)
[Link](['Name', 'Age'])
[Link]([['Alice', 25], ['Bob', 30]])
# Read:
with open('[Link]') as f:
Zero to Advanced Python Course Page 47
reader = [Link](f)
for row in reader:
print(row['Name'], row['Age'])
JSON files:
import json
data = {'name': 'Rahul', 'scores': [90, 85, 92]}
# Write:
with open('[Link]', 'w') as f:
[Link](data, f, indent=4)
# Read:
with open('[Link]') as f:
loaded = [Link](f)
# String:
s = [Link](data) # to string
d = [Link](s) # from string
os module:
import os
[Link]() # current directory
[Link]('.') # list files
[Link]('a/b/c') # create nested dirs
[Link]('a','[Link]')# 'a/[Link]' (cross-platform)
[Link]('[Link]')
[Link]('[Link]', '[Link]')
[Link]('[Link]')
Zero to Advanced Python Course Page 48
Practice Questions
1. Why should you always use 'with' when opening files? 2. What is the difference between 'w' and 'a' mode? 3. How
do you read a file line by line without loading all into memory? 4. How do you handle a file that might not exist? 5.
What is the difference between [Link] and [Link]? Coding Challenges: C1. Write a word frequency counter
that reads a .txt file and outputs the top 10 words. C2. Create a simple student grade manager using CSV read/write.
Zero to Advanced Python Course Page 49
MODULE
09 Exception Handling
try / except / else / finally
Exceptions — runtime errors that break program flow.
Basic try-except:
try:
x = int(input('Enter number: '))
print(10 / x)
except ValueError:
print('Invalid input!')
except ZeroDivisionError:
print('Cannot divide by zero!')
Multiple exceptions in one line:
except (ValueError, TypeError) as e:
print(f'Error: {e}')
Catch all (avoid in production):
except Exception as e:
print(f'Unexpected error: {e}')
else — runs if NO exception occurred:
try:
result = 10 / 2
except ZeroDivisionError:
print('Error!')
Zero to Advanced Python Course Page 50
else:
print(f'Result: {result}') # runs
finally — ALWAYS runs (cleanup code):
try:
f = open('[Link]')
data = [Link]()
except FileNotFoundError:
print('File missing!')
finally:
print('Done') # runs always
Custom Exceptions & Exception Hierarchy
Common built-in exceptions:
ValueError — wrong value type
TypeError — wrong type
IndexError — list index out of range
KeyError — dict key not found
AttributeError — object has no attribute
NameError — variable not defined
FileNotFoundError — file missing
ZeroDivisionError — divide by zero
OverflowError — numeric result too large
RecursionError — max recursion exceeded
StopIteration — iterator exhausted
ImportError — module not found
Zero to Advanced Python Course Page 51
RuntimeError — generic runtime error
Custom exception classes:
class InsufficientFundsError(Exception):
def __init__(self, amount, balance):
[Link] = amount
[Link] = balance
super().__init__(
f'Cannot withdraw {amount}, balance is {balance}')
def withdraw(balance, amount):
if amount > balance:
raise InsufficientFundsError(amount, balance)
return balance - amount
try:
withdraw(100, 200)
except InsufficientFundsError as e:
print(e)
raise — manually trigger exception:
def divide(a, b):
if b == 0:
raise ValueError('b cannot be zero')
return a / b
raise...from (exception chaining):
try:
Zero to Advanced Python Course Page 52
int('abc')
except ValueError as e:
raise RuntimeError('Conversion failed') from e
Practice Questions
1. What is the difference between except Exception and except BaseException? 2. When does the else block in
try-except run? 3. Is finally always guaranteed to run? (Think: os._exit()) 4. What is exception chaining? Use
raise...from. 5. How do you create a custom exception class? Coding Challenges: C1. Write a safe integer input
function that keeps asking until valid input is provided. C2. Create a BankAccount class with custom exceptions for
overdraft and invalid deposits.
Zero to Advanced Python Course Page 53
MODULE Object-Oriented Programming —
10
Complete Guide
Class & Object Basics
OOP — real-world entities ko code mein model karna.
Class = blueprint, Object = instance of class.
class Animal:
# Class variable (shared by all instances)
kingdom = 'Animalia'
def __init__(self, name, sound):
# Instance variables (unique to each object)
[Link] = name
[Link] = sound
def speak(self):
return f'{[Link]} says {[Link]}'
def __str__(self):
return f'Animal({[Link]})'
# Create objects:
dog = Animal('Dog', 'Woof')
cat = Animal('Cat', 'Meow')
print([Link]()) # Dog says Woof
print([Link]) # Animalia
print([Link]) # Animalia (inherited from class)
Zero to Advanced Python Course Page 54
Inheritance (All Types)
Inheritance — ek class dusri class ki properties inherit karti hai.
Single Inheritance:
class Dog(Animal):
def __init__(self, name, breed):
super().__init__(name, 'Woof') # call parent
[Link] = breed
def fetch(self):
return f'{[Link]} fetches the ball!'
buddy = Dog('Buddy', 'Labrador')
print([Link]()) # inherited method
print([Link]()) # new method
Multiple Inheritance:
class Flyable:
def fly(self): return 'Flying!'
class Swimmable:
def swim(self): return 'Swimming!'
class Duck(Animal, Flyable, Swimmable):
pass
d = Duck('Duck', 'Quack')
print([Link]()) # Flying!
Zero to Advanced Python Course Page 55
print([Link]()) # Swimming!
MRO (Method Resolution Order):
print(Duck.__mro__) # C3 linearization algorithm
Multilevel Inheritance:
class Animal: ...
class Dog(Animal): ...
class Puppy(Dog): ...
isinstance() and issubclass():
isinstance(buddy, Dog) # True
isinstance(buddy, Animal) # True (Dog inherits Animal)
issubclass(Dog, Animal) # True
Encapsulation & Properties
Encapsulation — data ko hide karna, controlled access dena.
Access modifiers:
[Link] # public — accessible anywhere
self._name # protected — convention: don't access outside
self.__name # private — name mangling applies
class BankAccount:
def __init__(self, owner, balance):
[Link] = owner
self.__balance = balance # private
@property
Zero to Advanced Python Course Page 56
def balance(self):
return self.__balance
@[Link]
def balance(self, amount):
if amount < 0:
raise ValueError('Balance cannot be negative')
self.__balance = amount
def deposit(self, amount):
if amount <= 0:
raise ValueError('Deposit must be positive')
self.__balance += amount
acc = BankAccount('Rahul', 1000)
print([Link]) # 1000 (via property getter)
[Link] = 2000 # calls setter
[Link] = -100 # raises ValueError!
Polymorphism & Abstraction
Polymorphism — same interface, different behavior.
Method Overriding:
class Shape:
def area(self):
raise NotImplementedError
class Circle(Shape):
Zero to Advanced Python Course Page 57
def __init__(self, r): self.r = r
def area(self): return 3.14 * self.r ** 2
class Rectangle(Shape):
def __init__(self, w, h): self.w, self.h = w, h
def area(self): return self.w * self.h
shapes = [Circle(5), Rectangle(4, 6)]
for s in shapes:
print([Link]()) # polymorphic call!
Abstract Base Classes (ABC):
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self): pass
@abstractmethod
def perimeter(self): pass
# Shape() → TypeError! Cannot instantiate abstract class
# Subclass MUST implement area() and perimeter()
Duck Typing — 'If it walks like a duck...'
def make_it_speak(animal):
[Link]() # works for any object with speak()
# Python cares about behavior, not type!
Magic / Dunder Methods
Zero to Advanced Python Course Page 58
Dunder methods — double underscore se start/end. Python ka protocol.
class Vector:
def __init__(self, x, y):
self.x, self.y = x, y
def __repr__(self): # developer repr
return f'Vector({self.x}, {self.y})'
def __str__(self): # user-friendly string
return f'({self.x}, {self.y})'
def __add__(self, other): # + operator
return Vector(self.x + other.x, self.y + other.y)
def __sub__(self, other): # - operator
return Vector(self.x - other.x, self.y - other.y)
def __mul__(self, scalar): # * operator
return Vector(self.x * scalar, self.y * scalar)
def __len__(self): # len()
return int((self.x**2 + self.y**2)**0.5)
def __eq__(self, other): # == operator
return self.x == other.x and self.y == other.y
def __lt__(self, other): # < operator
return len(self) < len(other)
Zero to Advanced Python Course Page 59
def __bool__(self): # bool()
return self.x != 0 or self.y != 0
def __getitem__(self, index): # v[0], v[1]
return (self.x, self.y)[index]
def __iter__(self): # for x in v
yield self.x
yield self.y
def __contains__(self, val): # 'in' operator
return val in (self.x, self.y)
v1 = Vector(3, 4)
v2 = Vector(1, 2)
print(v1 + v2) # (4, 6)
print(len(v1)) # 5 (3-4-5 triangle)
print(v1[0]) # 3
print(3 in v1) # True
Class Methods, Static Methods, Properties
@classmethod — takes cls (class itself) as first arg:
class Employee:
company = 'TechCorp'
employee_count = 0
def __init__(self, name, salary):
[Link] = name
Zero to Advanced Python Course Page 60
[Link] = salary
Employee.employee_count += 1
@classmethod
def from_string(cls, emp_str):
name, salary = emp_str.split('-')
return cls(name, int(salary))
@classmethod
def get_count(cls):
return cls.employee_count
@staticmethod
def validate_salary(s):
return s > 0
e = Employee.from_string('Rahul-50000') # alt constructor
print(Employee.get_count()) # 1
print(Employee.validate_salary(50000)) # True
Practice Questions
1. What is the difference between class variable and instance variable? 2. Explain MRO and the diamond problem in
multiple inheritance. 3. What is the difference between __str__ and __repr__? 4. When would you use
@classmethod vs @staticmethod? 5. Explain Python's name mangling for private attributes. 6. What is duck typing?
How is it different from strict type checking? 7. What is the difference between isinstance() and type()? 8. How does
@property work? What problem does it solve? Coding Challenges: C1. Design a full Library Management System
with Book, Member, and Library classes. C2. Create a Vector class supporting all arithmetic operators and
comparison.
Zero to Advanced Python Course Page 61
MODULE
11 Advanced Python Concepts
List Comprehension (Deep)
List comprehension — concise way to create lists.
Syntax: [expression for item in iterable if condition]
Basic:
squares = [x**2 for x in range(10)]
With condition:
evens = [x for x in range(20) if x % 2 == 0]
Nested:
matrix = [[i*j for j in range(1,4)] for i in range(1,4)]
# [[1,2,3],[2,4,6],[3,6,9]]
Flatten nested list:
nested = [[1,2,3],[4,5],[6]]
flat = [x for sublist in nested for x in sublist]
# [1,2,3,4,5,6]
Dict comprehension:
{k: v for k, v in zip('abc', [1,2,3])}
# {'a':1, 'b':2, 'c':3}
Set comprehension:
{x**2 for x in [-2,-1,0,1,2]}
# {0, 1, 4}
Zero to Advanced Python Course Page 62
Generator expression (lazy — no list created):
gen = (x**2 for x in range(1000000)) # no memory usage!
print(next(gen)) # 0
print(sum(gen)) # rest of squares
Ternary in comprehension:
labels = ['even' if x%2==0 else 'odd' for x in range(6)]
# ['even','odd','even','odd','even','odd']
Generators & Iterators
Iterator — object with __iter__() and __next__() methods.
Generator — function that uses 'yield' to produce values lazily.
Custom iterator:
class CountUp:
def __init__(self, start, end):
[Link] = start
[Link] = end
def __iter__(self):
return self
def __next__(self):
if [Link] > [Link]:
raise StopIteration
val = [Link]
[Link] += 1
Zero to Advanced Python Course Page 63
return val
for n in CountUp(1, 5):
print(n) # 1 2 3 4 5
Generator function:
def fibonacci():
a, b = 0, 1
while True:
yield a
a, b = b, a + b
fib = fibonacci()
for _ in range(10):
print(next(fib)) # 0 1 1 2 3 5 8 13 21 34
yield from:
def chain(*iterables):
for it in iterables:
yield from it
list(chain([1,2],[3,4])) # [1,2,3,4]
send() — two-way generator communication:
def accumulator():
total = 0
while True:
value = yield total
total += value
Zero to Advanced Python Course Page 64
acc = accumulator()
next(acc) # prime the generator
[Link](10) # 10
[Link](20) # 30
Decorators
Decorator — function jo doosri function ko wrap karta hai. Adds behavior.
Basic decorator:
def timer(func):
import time
def wrapper(*args, **kwargs):
start = [Link]()
result = func(*args, **kwargs)
end = [Link]()
print(f'{func.__name__} ran in {end-start:.4f}s')
return result
return wrapper
@timer
def slow_function():
import time; [Link](1)
slow_function() # slow_function ran in 1.0001s
[Link] — preserve function metadata:
from functools import wraps
def timer(func):
Zero to Advanced Python Course Page 65
@wraps(func) # preserves __name__, __doc__
def wrapper(*args, **kwargs):
...
return wrapper
Decorator with arguments:
def repeat(times):
def decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
for _ in range(times):
func(*args, **kwargs)
return wrapper
return decorator
@repeat(3)
def say_hello():
print('Hello!')
say_hello() # prints Hello! 3 times
Stacking decorators:
@timer
@repeat(2)
def greet(): print('Hi!')
# Applied bottom-up: repeat first, then timer
Class decorators:
class Singleton:
Zero to Advanced Python Course Page 66
_instances = {}
def __call__(self, cls):
if cls not in self._instances:
self._instances[cls] = cls()
return self._instances[cls]
Context Managers
Context manager — 'with' statement ke saath use hota hai.
Ensures setup/teardown happens even if error occurs.
Using [Link]:
from contextlib import contextmanager
@contextmanager
def timer():
import time
start = [Link]()
try:
yield # code in 'with' block runs here
finally:
print(f'Time: {[Link]()-start:.2f}s')
with timer():
import time; [Link](1)
# Time: 1.00s
Class-based context manager:
class DatabaseConnection:
Zero to Advanced Python Course Page 67
def __init__(self, url):
[Link] = url
def __enter__(self):
print(f'Connecting to {[Link]}')
return self # value returned to 'as' variable
def __exit__(self, exc_type, exc_val, exc_tb):
print('Disconnecting...')
# return True to suppress exceptions
return False
with DatabaseConnection('localhost:5432') as db:
print('Executing query...')
Regex (Regular Expressions)
Regex — pattern matching for strings.
import re
Basic patterns:
. any char except newline
^ start of string
$ end of string
* 0 or more
+ 1 or more
? 0 or 1
\d digit [0-9]
Zero to Advanced Python Course Page 68
\w word char [a-zA-Z0-9_]
\s whitespace
\D non-digit
[] character class
| OR
() group
{n} exactly n times
{m,n} between m and n times
Functions:
[Link](pattern, string) # match at START only
[Link](pattern, string) # first match anywhere
[Link](pattern, string) # list of all matches
[Link](pattern, string) # iterator of match objects
[Link](pattern, repl, string)# replace matches
[Link](pattern, string) # split by pattern
[Link](pattern) # compile for reuse
Examples:
# Validate email:
pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
[Link](pattern, 'user@[Link]') # Match object
# Extract phone numbers:
phones = [Link](r'\d{10}', 'Call 9876543210 or 8765432109')
# ['9876543210', '8765432109']
# Replace whitespace:
Zero to Advanced Python Course Page 69
[Link](r'\s+', ' ', 'hello world') # 'hello world'
# Groups:
m = [Link](r'(\d+)-(\d+)', 'Phone: 123-456')
[Link](1) # '123'
[Link](2) # '456'
Multithreading & Multiprocessing
Threading — I/O-bound tasks ke liye (file, network, DB).
Multiprocessing — CPU-bound tasks ke liye (computation).
Threading:
import threading
def download(url):
print(f'Downloading {url}...')
import time; [Link](2)
print(f'Done: {url}')
urls = ['url1', 'url2', 'url3']
threads = [[Link](target=download, args=(u,)) for u in urls]
for t in threads: [Link]()
for t in threads: [Link]() # wait for all
# Thread-safe counter using Lock:
lock = [Link]()
counter = 0
def safe_increment():
Zero to Advanced Python Course Page 70
global counter
with lock:
counter += 1
Multiprocessing:
from multiprocessing import Pool
def cpu_task(n):
return sum(i**2 for i in range(n))
with Pool(processes=4) as pool:
results = [Link](cpu_task, [10**6, 10**6, 10**6, 10**6])
GIL (Global Interpreter Lock):
Python ke threads CANNOT run Python code in parallel due to GIL.
For CPU-bound: use multiprocessing or [Link].
For I/O-bound: threading is fine (GIL released during I/O).
[Link] (high-level):
from [Link] import ThreadPoolExecutor
with ThreadPoolExecutor(max_workers=4) as executor:
futures = [[Link](download, u) for u in urls]
results = [[Link]() for f in futures]
Practice Questions
1. What is the difference between a generator and a list comprehension? 2. How does yield differ from return? 3.
Explain the decorator pattern — why use it? 4. What is the GIL? How does it affect multithreading? 5. Difference
between threading and multiprocessing? 6. What is a context manager and when would you write your own? 7. What
is [Link] vs [Link]? Coding Challenges: C1. Write a retry decorator that retries a function up to N times if it
raises an exception. C2. Create an infinite Fibonacci generator and use it to print the first 20 numbers.
Zero to Advanced Python Course Page 71
MODULE
12 Libraries — NumPy & Pandas
NumPy Basics
NumPy — Numerical Python. Fast array operations using C under the hood.
import numpy as np
Creating arrays:
[Link]([1, 2, 3, 4]) # 1D array
[Link]([[1,2],[3,4]]) # 2D array (matrix)
[Link]((3, 4)) # 3x4 zeros
[Link]((2, 3)) # 2x3 ones
[Link](3) # 3x3 identity matrix
[Link](0, 10, 2) # [0,2,4,6,8]
[Link](0, 1, 5) # [0,.25,.5,.75,1.0]
[Link](3, 3) # random floats [0,1)
[Link](0, 100, (3,3)) # random ints
Array properties:
a = [Link]([[1,2,3],[4,5,6]])
[Link] # (2, 3)
[Link] # 2
[Link] # 6
[Link] # int64
Operations (vectorized — no loops needed!):
a = [Link]([1,2,3,4])
Zero to Advanced Python Course Page 72
a * 2 # [2,4,6,8]
a ** 2 # [1,4,9,16]
[Link](a) # element-wise sqrt
a + a # [2,4,6,8]
Indexing & slicing:
m = [Link]([[1,2,3],[4,5,6],[7,8,9]])
m[1, 2] # 6
m[:, 1] # [2,5,8] — column 1
m[0:2, 0:2] # [[1,2],[4,5]] — submatrix
Boolean indexing:
a[a > 2] # [3,4] — filter by condition
Math operations:
[Link](m), [Link](m), [Link](m)
[Link](m), [Link](m)
[Link](m, axis=0) # column sums
[Link](m, axis=1) # row sums
Pandas Basics
Pandas — data manipulation and analysis. Built on NumPy.
import pandas as pd
Series (1D labeled array):
s = [Link]([10, 20, 30], index=['a','b','c'])
s['a'] # 10
Zero to Advanced Python Course Page 73
s[s > 15] # b 20, c 30
DataFrame (2D table):
data = {
'Name': ['Alice','Bob','Charlie'],
'Age': [25, 30, 35],
'City': ['Delhi','Mumbai','Bangalore']
df = [Link](data)
Reading data:
df = pd.read_csv('[Link]')
df = pd.read_excel('[Link]')
df = pd.read_json('[Link]')
Exploration:
[Link](5) # first 5 rows
[Link](5) # last 5 rows
[Link]() # column types, nulls
[Link]() # statistics
[Link] # (rows, cols)
[Link] # column names
[Link] # column data types
Selection:
df['Name'] # single column (Series)
df[['Name','Age']] # multiple columns
[Link][0] # first row by position
Zero to Advanced Python Course Page 74
[Link][0, 'Name'] # by label
df[df['Age'] > 28] # filter rows
Data cleaning:
[Link]().sum() # count nulls per column
[Link]() # drop rows with any null
[Link](0) # fill nulls with 0
df.drop_duplicates() # remove duplicate rows
df['Age'] = df['Age'].astype(int)
Aggregation:
[Link]('City')['Age'].mean()
[Link]('City').agg({'Age': ['mean','max']})
df.pivot_table(values='Age', index='City', aggfunc='mean')
Saving:
df.to_csv('[Link]', index=False)
df.to_excel('[Link]', index=False)
Practice Questions
1. Why is NumPy faster than Python lists for numerical operations? 2. What is broadcasting in NumPy? 3. Difference
between loc and iloc in Pandas? 4. How do you handle missing data in Pandas? 5. What does groupby() return? How
is it used? Coding Challenges: C1. Load a CSV file, find the top 5 rows by a numeric column, and save to new CSV.
C2. Create a NumPy matrix multiplication function and verify against [Link]().
Zero to Advanced Python Course Page 75
MODULE
13 Real-World Mini Projects
Project 1: Calculator (CLI)
def calculator():
print('=== Python Calculator ===')
print('Operations: + - * / // % **')
while True:
try:
expression = input('\nEnter expression (or q to quit): ')
if [Link]() == 'q':
print('Goodbye!')
break
# Safe eval using restricted globals:
result = eval(expression, {'__builtins__': {}},
{'abs': abs, 'round': round})
print(f'Result: {result}')
except ZeroDivisionError:
print('Error: Division by zero!')
except Exception as e:
print(f'Invalid expression: {e}')
if __name__ == '__main__':
calculator()
Project 2: Password Generator
import random
Zero to Advanced Python Course Page 76
import string
def generate_password(length=12, use_upper=True,
use_digits=True, use_symbols=True):
chars = string.ascii_lowercase
if use_upper: chars += string.ascii_uppercase
if use_digits: chars += [Link]
if use_symbols: chars += [Link]
# Ensure at least one of each required type:
password = []
if use_upper: [Link]([Link](string.ascii_uppercase))
if use_digits: [Link]([Link]([Link]))
if use_symbols: [Link]([Link]([Link]))
[Link]([Link](string.ascii_lowercase))
while len(password) < length:
[Link]([Link](chars))
[Link](password)
return ''.join(password)
def main():
print('=== Password Generator ===')
length = int(input('Password length (default 12): ') or 12)
n = int(input('How many passwords? ') or 5)
for i in range(n):
print(f' {i+1}. {generate_password(length)}')
Zero to Advanced Python Course Page 77
if __name__ == '__main__':
main()
Project 3: File Organizer
import os
import shutil
from pathlib import Path
CATEGORIES = {
'Images': ['.jpg','.jpeg','.png','.gif','.bmp','.svg'],
'Videos': ['.mp4','.mov','.avi','.mkv'],
'Documents': ['.pdf','.doc','.docx','.txt','.xlsx','.pptx'],
'Audio': ['.mp3','.wav','.flac','.aac'],
'Code': ['.py','.js','.html','.css','.java','.cpp'],
'Archives': ['.zip','.tar','.gz','.rar'],
'Others': []
def get_category(extension):
for category, exts in [Link]():
if [Link]() in exts:
return category
return 'Others'
def organize_folder(folder_path):
folder = Path(folder_path)
moved = 0
Zero to Advanced Python Course Page 78
for file in [Link]():
if file.is_file():
category = get_category([Link])
dest = folder / category
[Link](exist_ok=True)
[Link](str(file), str(dest / [Link]))
moved += 1
print(f' Moved {[Link]} → {category}/')
print(f'\nOrganized {moved} files!')
if __name__ == '__main__':
path = input('Enter folder path to organize: ')
organize_folder(path)
Project 4: CLI Todo App
import json
from pathlib import Path
from datetime import datetime
TODO_FILE = Path('[Link]')
def load_todos():
if TODO_FILE.exists():
return [Link](TODO_FILE.read_text())
return []
def save_todos(todos):
TODO_FILE.write_text([Link](todos, indent=2))
Zero to Advanced Python Course Page 79
def add_todo(title, priority='medium'):
todos = load_todos()
todo = {
'id': len(todos) + 1,
'title': title,
'done': False,
'priority': priority,
'created': [Link]().isoformat()
[Link](todo)
save_todos(todos)
print(f'Added: {title}')
def list_todos():
todos = load_todos()
if not todos:
print('No todos!')
return
for t in todos:
status = '[x]' if t['done'] else '[ ]'
print(f"{t['id']}. {status} [{t['priority'].upper()}] {t['title']}")
def main():
print('=== Python Todo App ===')
while True:
print('\n1. List 2. Add 3. Complete 4. Quit')
Zero to Advanced Python Course Page 80
choice = input('Choose: ')
if choice == '1': list_todos()
elif choice == '2':
title = input('Task: ')
priority = input('Priority (low/medium/high): ') or 'medium'
add_todo(title, priority)
elif choice == '4': break
if __name__ == '__main__':
main()
Zero to Advanced Python Course Page 81
MODULE Revision Cheatsheet & Top Interview
14
Questions
Python Cheatsheet — Quick Reference
DATA TYPES: int, float, complex, str, bool, None list [], tuple (), set {}, dict {k:v}, frozenset STRING TRICKS: s[::-1] #
reverse [Link]() # split on whitespace ' '.join(lst) # join list f'{val:.2f}' # 2 decimal places [Link]() # remove whitespace
LIST TRICKS: sorted(lst, key=lambda x: x[1]) # sort by 2nd element lst[::-1] # reverse list(set(lst)) # deduplicate [x for
x in lst if condition] # filter DICT TRICKS: {v:k for k,v in [Link]()} # invert dict sorted(d, key=[Link]) # sort by value
[Link](k, default) # safe access FUNCTIONS: lambda x: x**2 map(func, lst) filter(func, lst) zip(lst1, lst2) enumerate(lst,
start=1) OOP: class A(B): pass # inheritance super().__init__() # parent constructor @property # getter
@staticmethod @classmethod __str__, __repr__, __len__, __eq__ COMPREHENSIONS: [x**2 for x in range(10)]
{k:v for k,v in items} {x for x in lst} (x for x in lst) # generator EXCEPTION HANDLING: try/except/else/finally raise
ValueError('msg') class CustomError(Exception): pass USEFUL MODULES: os, sys, pathlib, json, csv collections
(Counter, defaultdict, deque) itertools, functools, datetime re, math, random, string
Top 30 Python Interview Questions
1. What are Python's key features? (interpreted, dynamically typed, GC, OOP) 2. Mutable vs immutable types? 3.
What is the GIL? How does it affect performance? 4. Difference between deepcopy and shallow copy? 5. What are
Python decorators? Write one from scratch. 6. Explain generators vs list comprehensions. 7. What is *args and
**kwargs? 8. Explain LEGB scope rule. 9. What is a closure? Write an example. 10. Difference between __str__ and
__repr__? 11. What is method resolution order (MRO)? 12. What is duck typing? 13. Explain the difference between
is and ==. 14. What is a lambda function? Limitations? 15. What are context managers? How to write one? 16.
Difference between @staticmethod and @classmethod? 17. How does Python manage memory? (reference
counting + GC) 18. What is monkey patching? 19. What are metaclasses? 20. Explain list comprehension vs
map/filter. 21. How to make a class iterable? 22. What is a named tuple? Advantages? 23. Explain
try/except/else/finally flow. 24. What is a Singleton pattern? Implement it. 25. What is pickling/unpickling? 26. How do
you profile Python code? 27. Difference between threading and multiprocessing? 28. What is asyncio? When to use
it? 29. Explain Python's garbage collection. 30. What are dataclasses? (Python 3.7+) Bonus: from dataclasses import
dataclass @dataclass class Point: x: float y: float def distance(self): return (self.x**2 + self.y**2)**0.5
Project Ideas for Your Portfolio
BEGINNER: • Number guessing game • Simple quiz app • Unit converter • Rock-Paper-Scissors • Basic calculator
INTERMEDIATE: • Web scraper (BeautifulSoup/requests) • Weather app (API integration) • Personal finance tracker
(Pandas + CSV) • URL shortener (Flask) • CLI task manager (argparse) • PDF text extractor ADVANCED: • REST
API (FastAPI + SQLAlchemy) • ML model deployment (Flask + scikit-learn) • Telegram bot (python-telegram-bot) •
Automated trading strategy backtester • Real-time chat app (websockets) • Image classification
(TensorFlow/PyTorch) • Distributed web crawler DATA SCIENCE: • EDA on Kaggle dataset (Pandas + Matplotlib) •
Stock price predictor (LSTM) • Sentiment analysis • Customer segmentation (K-Means) • Recommendation system
Zero to Advanced Python Course Page 82