Python in one line per lesson
Module 1: Start coding
- Your first program: print() shows output and Python runs top to bottom; read an error from its last line: the type, the message, then the line number.
- Numbers and names: // drops the fraction, % gives the remainder, runs first and right to left; = points a name at a value, it is not an equation.
- Text and input: input() returns text; wrap it in int() or float() before doing maths, and str() a number before joining it to text.
- Types and neat output: Values have types (int, float, str, bool, None); print money with f"{x:.2f}"; names cannot start with a digit or be a keyword.
Module 2: Decisions and loops
- if / elif / else: == compares and = stores; an elif ladder runs only the first True branch, so put the strictest condition first.
- Combining conditions: and needs both, or needs one, not flips; 0, "" and None are falsy; write ch == "a" or ch == "e", never ch == "a" or "e".
- Loops: while and for: while repeats while a condition is True (do not forget the update); range(a, b, s) goes from a up to but not including b.
- Loop patterns: Start the result before the loop, update it inside, use it after; continue skips a round, break leaves, loop else runs only if there was no break.
- Nested loops and patterns: The outer loop counts rows, the inner loop fills a row; end each row with print(), and work out spaces and stars per row with a small table.
- Number programs: n % 10 is the last digit and n // 10 drops it; a product starts at 1, a prime check needs a flag or a loop else, and you should always test 0, 1 and 2.
Module 3: Functions
- Writing functions: def makes a function, a call runs it; return hands a value back (no return means None); defaults go last in the header, keywords go last in the call.
- Scope and flow of execution: Names assigned inside a function are local to that call; reading a global is fine, assigning to it needs global (or better, return the new value).
- Modules: math, random and friends: import m → m.f(), from m import f → f(); randint(a, b) includes b, randrange(a, b) doesn't; guard demo code with if name == "main":.
- Good functions: one job, docs and tests: One job per function, a docstring on top, and assert condition, "message" tests (no brackets) for normal, edge and boundary cases.
Module 4: Strings
- Indexing and slicing: s[0] first, s[-1] last; s[a:b] includes a but not b; s[::-1] reverses; strings can't be changed in place, so build a new one.
- String methods: Methods return a new string (save it!); find gives -1 but index crashes; split → list, "sep".join(list) → string, partition → 3-tuple.
- String programs for practicals: Every string program is: loop over the characters, test each with in or an is… method, update a counter or build a new string; return True only after the loop.
- Text puzzles: ciphers and anagrams: ord turns a character into its code and chr back; shift letters with (pos + k) % 26; anagrams have equal sorted() letters.
Module 5: Lists and tuples
- Lists: append adds one item, extend adds many; remove takes a value, pop an index; sort() changes the list and returns None, sorted() returns a new list.
- Lists and names: the aliasing trap: b = a gives one list two names; copy with a[:], list(a) or a.copy() (and copy.deepcopy for nested lists); build grids with a loop, never [[0]n]n.
- List patterns: Start a max/min at lst[0], a sum at 0; return -1 only after the whole search loop; swap with a[i], a[j] = a[j], a[i].
- Nested lists: tables and matrices: A table is a list of rows: m[r][c]; len(m) is rows, len(m[0]) is columns; build each new row inside the loop.
- Stack, queue and list comprehensions: Stack: append + pop() (LIFO); queue: append + pop(0) or deque.popleft() (FIFO); [f(x) for x in xs if cond] builds a new list.
- Tuples: Tuples are fixed lists: the comma makes one ((5,), not (5)); a, b = b, a swaps; return x, y returns a tuple you can unpack.
Module 6: Dictionaries and sets
- Dictionaries: d[k] crashes on a missing key, d.get(k, default) does not; in checks keys; count with d[x] = d.get(x, 0) + 1.
- Records: lists of dicts and dicts of lists: A record is a dict, a table is a list of dicts; group with d.setdefault(k, []).append(x); use fromkeys only with immutable starting values.
- Sets, and choosing the right collection: A set keeps unique values (set() is empty, {} is a dict); & | - combine sets; keys must be hashable, so use a tuple, never a list.
Module 7: Errors and debugging
- Reading errors: Syntax errors stop the file before it runs, runtime errors stop at the bad line, logical errors give wrong answers silently; read a traceback from the bottom up.
- Handling errors: try the risky lines, except a named error, else runs only on success, finally always runs; the first matching except wins, so put specific ones first; raise your own errors.
- Debugging: Debug by finding the first wrong value (trace table or labelled prints); never use a bare except:, catch only the errors you expect.
Module 8: Files
- Reading files: Open files with with open(path) as f:; read() gives one string, readline() one line (with \n, "" at the end), readlines() a list; strip each line.
- Writing files: "w" wipes, "a" appends, "r+" overwrites in place; write adds no newline and returns the count; tell() is where you are, seek(n) jumps there.
- Text-file programs: Text-file programs: read, then loop over characters, words (split()) or lines; strip punctuation and lowercase before comparing; open the output file once.
- CSV and JSON: csv.reader/csv.writer (with newline="") for tables, values come back as strings; json.dump/json.load save dicts and lists as they are (keys become strings).
Module 9: Object-oriented programming
- Classes and objects: A class is a blueprint; init fills each new object through self; print uses str, lists and the shell use repr.
- Working with objects: Class attributes are shared, self.x is per object; eq/lt make objects comparable and sortable; @classmethod gets cls (alternative constructors), @staticmethod gets nothing.
- Encapsulation: x means internal, x is name-mangled to Classx; @property (plus @x.setter) guards an attribute while keeping obj.x syntax.
- Inheritance: class Child(Parent) reuses and overrides; super() calls the next class in the MRO; check the order with Cls.mro().
- Abstraction and polymorphism: Polymorphism and duck typing: same call, each object answers its own way; ABCs force subclasses to implement methods; no overloading (the last def wins), but operators overload through dunders.
- Object creation and design: new creates and returns the object, init fills it; slots fixes attributes; @dataclass writes the boilerplate; Enum names constants; Singleton, Factory and Observer are everyday patterns.
Module 10: NumPy and pandas
- NumPy arrays: A NumPy array holds one type; arr 2, arr + arr and np.sqrt(arr) work on every element at once (vectorised); read shape, ndim, size, dtype.
- Working with arrays: m[r, c], m[:, c], m[r1:r2, c1:c2] slice 2D arrays; axis=0 gives per-column answers, axis=1 per-row; m[m 75] filters (use &, | with brackets); a slice is a view, so .copy() when you need independence.
- pandas Series: A Series is a labelled 1D array: make it from a list, dict, ndarray or scalar; loc uses labels (slice end included), iloc uses positions; maths lines up by label.
- DataFrames: A DataFrame is a table of Series sharing one index; df["col"] is a Series, df[["a", "b"]] a DataFrame; loc[rows, cols] by label, iloc by position; filter with df[mask] and &/|.
- Changing and summarising: Add columns with df["new"] = ...; rename, drop, sortvalues, fillna, dropna return new frames (assign back); df.groupby("key")["col"].sum() summarises; change cells with one df.loc[mask, col] = ....
- CSV in, charts out: pd.readcsv(path) loads a table (header=None if there is no header line); df.tocsv(path, index=False) saves one; plt.plot for trends, plt.bar for categories, plt.hist for spread, always with a title and axis labels.
Module 11: Functions in depth
Module 12: Iteration and the standard toolkit
- Comprehensions in depth: [expr for x in it if cond]: filter if at the end, a if c else b at the front; {k: v ...} makes a dict, {v ...} a set; nested fors read like nested loops.
- Iterators and generators: for uses iter() and next() until StopIteration; a generator (yield or (x for x in …)) makes values lazily, saves memory and can be used only once.
- Built-ins that save you: enumerate for positions, zip for parallel lists (stops at the shortest), any/all for conditions, key= for sorting (stable, use a tuple for ties), divmod for quotient and remainder.
- The collections module: Counter counts (mostcommon(k)), defaultdict groups and totals, deque gives O(1) ends (with maxlen), namedtuple names tuple fields, OrderedDict adds movetoend.
- heapq and bisect: heapq is a min-heap on a list (h[0] smallest, push/pop O(log n)); negate for a max-heap, use nlargest(k, …) for top k; bisect searches and insort inserts into a sorted list in O(log n).
- itertools and functools: permutations (order matters), combinations (it doesn't), product (nested loops), accumulate (running totals), groupby (consecutive only, sort first), islice/chain for iterators; partial pre-fills arguments, cmptokey sorts with a compare function.
Module 13: Python under the hood
- Everything is an object: Names are labels on objects; == compares values, is compares identity (use it only for None); functions get a new label on the same object.
- Copies: assignment, shallow and deep: b = a copies nothing; copy.copy/.copy()/[:] copy only the outer object; copy.deepcopy copies everything inside too.
- Memory management: CPython frees an object when its reference count hits 0; the gc collector frees reference cycles; weakref points without keeping alive.
- How list, dict and set work: A list is a growing array (index O(1), in O(n), pop(0) O(n)); dict and set are hash tables (in O(1)) that need hashable keys.
- Bytecode, the GIL and the Python way: CPython compiles to bytecode and runs it in a VM; the GIL lets one thread run bytecode at a time, so threads help I/O, not CPU work.
Module 14: Exceptions, context managers and testing
- Advanced exceptions: Subclass Exception for your own errors (with a base class), chain with raise New(...) from e, and never return inside finally.
- Context managers: writing your own `with`: with calls enter (its return is the as name) and always exit; a truthy exit suppresses the error; with @contextmanager, wrap yield in try/finally.
- Logging instead of print: Log with levels (DEBUG < INFO < WARNING < ERROR < CRITICAL, default WARNING), set them up once with basicConfig, and raise when the caller must act.
- Testing: asserts, pytest, unittest and mocks: A test calls your code and asserts the result; pytest finds test functions (fixtures, parametrize, pytest.raises); unittest.mock fakes what you cannot control.
Module 15: Real-world Python
- Projects and packages: A package is a folder with init.py; imports search sys.path in order; venv + requirements.txt pin libraries; argparse reads options; type hints are labels Python does not enforce.
- Web APIs and JSON: requests.get/post(url, params=/json=, timeout=) returns a response: check statuscode or raiseforstatus(), then .json(); always set a timeout.
- Databases from Python: sqlite3: connect, cursor, execute(sql, (values,)) with ?, commit(), fetch; never build SQL with f-strings; with conn: is all-or-nothing.
Module 16: Concurrency
- Threads: Threads overlap waiting (I/O), not calculating (GIL); protect shared data with with lock:, pass work with queue.Queue, take locks in one fixed order.
- Processes: ProcessPoolExecutor/Pool run CPU-bound work on every core (each process has its own GIL); guard with if name == "main":, use top-level functions, and return results since memory is not shared.
- asyncio: async def makes a coroutine, await pauses it so others run; asyncio.gather runs many together (results in argument order); use waitfor for timeouts, a Semaphore for limits, and never block the loop.
Pack A: CBSE Class 12 Board Pack
- Binary files with pickle: pickle.dump(obj, f) writes one object to a file opened in wb/ab; pickle.load(f) reads one back, so loop until EOFError.
- Binary file programs: search, append, update: Search with a found flag; append with ab; update or delete by reading all records, changing the list, and rewriting with wb.
- CSV files, board style: Open CSV files with newline=""; writerow/writerows write, reader reads lists of strings; skip the header with next() and convert before maths.
- Stack programs: A stack is LIFO: push with append(), pop with pop(), peek with [-1], and always check for an empty stack before popping.
- SQL you can run: queries for the board: SELECT … FROM … WHERE … GROUP BY … HAVING … ORDER BY; use IS NULL, LIKE with % and , and never UPDATE or DELETE without WHERE unless you mean every row.
- Python + MySQL connectivity: connect → cursor → execute (with %s and a tuple) → commit() for changes or fetchone()/fetchall() for reading → close; rowcount counts affected or fetched rows.
- Board question types: output, errors, assertion-reason: Trace with a table; goes right to left; randint includes both ends; except clauses are tried top to bottom; in A-R, judge A and R separately, then ask "A because R?".
- Practical file, project and viva: Practical = lab test 12 + report file 7 + project 8 + viva 3; keep tested, commented programs for every practical-list item and be able to explain each line.
Pack B: College Semester Pack
- Recursion: Recursion = a base case answered directly + a call on a smaller problem; always return the recursive call; memoise repeated work (@lrucache).
- Searching and sorting: Linear search works anywhere (O(n)); binary search needs sorted data (O(log n)); bubble swaps neighbours, selection picks the minimum, insertion slides each item into place (all O(n²)).
- Automating files: os.listdir gives names (join them back with os.path.join); os.walk visits the whole tree; shutil.copy/move and os.makedirs(existok=True) organise; zipfile backs up; deleting is permanent.
- Regular expressions: Write regex as r"..."; search finds anywhere, fullmatch validates the whole text, findall lists all (tuples with groups), sub replaces (\1 reuses a group).
- Mini game: a campus adventure: A game is a while loop over (show, read, update); keep the world in dicts, clean input with .strip().lower(), seed random, and print exact messages so it is testable.