1.
Basic Syntax & Data Types
What: Python’s core containers are str, list, tuple, dict, plus set. Learn how they
store data, how to access them, how they differ (mutability, ordering), and common methods.
● Strings: immutable, indexed, sliceable. Methods: .lower(), .upper(),
.strip(), .split(), .join(), .replace(), .find().
○ Slice example: s[1:5], reverse: s[::-1].
● Lists: mutable, ordered. Methods: .append(), .extend(), .insert(), .pop(),
.remove(), .sort(), .reverse(), .copy().
● Tuples: immutable, ordered. Use for fixed collections; methods limited to .count()
and .index().
● Dictionaries: key→value mapping. Methods: .get(key, default), .keys(),
.values(), .items(), .update(), .pop(), .setdefault().
● Sets: unordered unique elements; operations: union, intersection, difference.
Pitfalls
● Mutability/sharing: b = a shares reference. Use [Link]() or [Link]()
for independent copies.
● Concatenation: + works for lists/strings/tuples but not dicts (use update()).
● Index errors if you access out-of-range.
Tiny example
lst = [1,2,3]
[Link](4) # [1,2,3,4]
t = (1,2,3)
d = {'a':1,'b':2}
s = "Hello".upper() # "HELLO"
Practice (2 min): Reverse a list in-place and without creating a new list. (Try
[Link]() and slicing.)
2. Functions & Recursion
What: def defines a function. Learn parameters, returns, *args, **kwargs, default values,
scope (local, global, nonlocal), and recursion basics.
Signature examples
def f(a, b=2, *args, **kwargs):
"""docstring"""
return a + b
●
● Return can be multiple values (tuples): return a, b.
● Recursion: base case + recursive case. Watch recursion depth and stack usage.
Python doesn’t optimize tail recursion.
Factorial (recursive)
def fact(n):
if n <= 1: return 1
return n * fact(n-1)
Pitfalls
● No base case → infinite recursion (RecursionError).
● Deep recursion is slow and memory-heavy vs. iteration.
Practice (2 min): Write a recursive function for Fibonacci (first two base cases). Compare
iterative vs recursive performance mentally.
3. Control Structures
What: if/elif/else, loops (for, while), break, continue, and the loop else clause.
● Truthiness: empty sequences are False, non-zero numbers True.
● For loops: iterate any iterable; use enumerate() for indices and zip() for parallel
iteration.
● While loops: run until condition false; break stops loop, continue skips to next
iteration.
● Loop else: executes if loop wasn’t terminated by break.
Comprehensions (compact iteration + filtering)
evens = [x for x in range(10) if x % 2 == 0]
squares = {x: x*x for x in range(5)} # dict comprehension
Pitfalls
● Modifying a list while iterating over it — iterate over a copy or build a new list.
● Off-by-one errors in indices.
Practice (2 min): Use enumerate to print index and value of a list; rewrite with a list
comprehension to square only odd numbers.
4. String Operations
What: slicing, reversing, palindrome check, character counts, and manipulations.
● Slicing: s[start:stop:step]. Reverse: s[::-1].
● Palindromes: s == s[::-1] (use .casefold() for case-insensitive).
Count vowels/consonants:
vowels = sum(1 for ch in [Link]() if ch in 'aeiou')
●
● Other methods: .split(), ' '.join(list), .replace(), .startswith(),
.endswith(), .find().
Pitfalls
● Unicode care: use .casefold() not .lower() for robust comparisons.
● Strings are immutable — operations return new strings.
Practice (2 min): Write a one-line expression to count vowels in a string using a generator
expression.
5. Mathematical Computations
What: Common computations (distance, area), number theory (GCD), factorials, and proper
use of math module.
● import math — use [Link](), [Link], [Link](x1-x2,y1-y2) for
distance.
GCD/LCM:
from math import gcd
lcm = lambda a,b: a*b // gcd(a,b)
●
● Factorial: [Link](n) (fast, implemented in C).
● Use pow(x, y, mod) for modular exponentiation.
Pitfalls
● Floating point precision — for comparisons use [Link]().
● For financial precision use [Link].
Practice (2 min): Compute LCM of 12 and 18 using gcd.
6. Object-Oriented Programming (OOP)
What: Classes, objects, attributes, methods, inheritance, __init__, super(),
polymorphism, and special methods.
Basic class
class Person:
def __init__(self, name): [Link] = name
def greet(self): return f"Hello, {[Link]}"
●
Inheritance & override
class Student(Person):
def __init__(self, name, roll):
super().__init__(name)
[Link] = roll
def greet(self): # override
return f"Hi {[Link]}, roll {[Link]}"
●
● Polymorphism: different classes implement same method signature (duck typing).
● Encapsulation: single underscore _x (convention), double __x (name mangling).
Pitfalls
● Mutable class variables shared across instances: prefer instance attributes.
● Overuse of inheritance when composition is better.
Practice (3 min): Create Shape base class with area() stub; implement Rectangle
subclass with width & height.
7. Functions for Data Processing
What: lambda (anonymous), map, filter, reduce, comprehensions, and collection
utilities.
Examples
doubles = list(map(lambda x: x*2, [1,2,3]))
evens = list(filter(lambda x: x%2==0, range(10)))
from functools import reduce
sum_all = reduce(lambda a,b: a+b, [1,2,3])
●
Comprehensions are often clearer:
doubles = [x*2 for x in arr]
●
● Set/dict ops: set1 & set2 (intersection), set1 | set2 (union), dict
comprehension {k:v for k,v in items if cond}.
● [Link] for frequency counts.
Pitfalls
● Overuse of lambda + map can hurt readability; comprehensions preferred for clarity.
● reduce can be replaced by builtins like sum().
Practice (2 min): Use a comprehension to get squares of even numbers from 0–9.
8. Operator Precedence & Variable
Naming
What: Understand precedence to avoid logic bugs; follow naming conventions.
● Important precedence highlights: () → ** → * / // % → + - → comparisons
→ not → and → or. Use parentheses to be explicit.
● is vs ==: == compares value, is compares identity (object).
● Naming (PEP8):
○ Use snake_case for variables/functions.
○ UPPER_SNAKE for constants.
○ Avoid shadowing built-ins (list, str, id).
○ Descriptive names: total_marks > tm.
Pitfalls
● Relying on precedence instead of parentheses → subtle bugs.
● Shadowing built-ins leads to confusing errors.
Practice (1 min): Which is evaluated first in 3 + 4 * 2 ** 2? (Add parentheses to show
your intended order.)
9. Error Handling & Best Practices
What: Use try/except properly, prefer specific exceptions, use with for resources, and
adopt good coding practices.
Try/except
try:
n = int(input())
except ValueError:
print("Please enter an integer")
finally:
cleanup()
●
● Catch specific exceptions (KeyError, IndexError, ValueError,
AttributeError) — avoid bare except: unless re-raising.
● Context managers: with open('[Link]') as f: data = [Link]() ensures
automatic close.
● Debugging & logging: prefer logging module over print for real projects; use
assertions during development.
● Best practices
○ Indentation: 4 spaces.
○ Use docstrings and type hints: def add(x: int, y: int) -> int:
...
○ Lint & format: flake8, black.
○ Unit tests: pytest or unittest.
○ Virtual environments: venv, pipenv, poetry.
Common Errors & Causes
● IndexError: accessing invalid index.
● KeyError: missing dict key (use .get()).
● AttributeError: calling method that doesn’t exist on type.
● TypeError: wrong operand types for operation.
Practice (2 min): Write a try/except block that attempts int(s) and prints a friendly
message if it fails.