# MSDEVBUILD (Multi-Stack Dev Build): full content > Free, practical learning by Suthahar Jegatheesan, Cloud, AI & Mobile Solutions Architect, that helps students and industry professionals build skills in cloud, AI, mobile, Python and system design. Short map: https://www.msdevbuild.com/llms.txt Every Python lesson runs real Python 3 in the browser (Pyodide). Example outputs below were produced by running the code. PY-101, AI-601, GD-301 and the other codes here are MSDEVBUILD course codes. They are not official Microsoft or Python Software Foundation certifications. ## PY-101 Python Core URL: https://www.msdevbuild.com/python/py-101/ Every Python fundamental in one course: basics, control flow, functions, collections, strings, files, errors, modules, OOP, generators and testing. Each topic comes alive, then you practise it live. Who it is for: Anyone starting Python, and anyone who uses AI-generated Python without being sure what it does. Every roadmap starts here. ### Module 1: Getting started with Python #### What is Python? URL: https://www.msdevbuild.com/python/py-101/what-is-python/ Python is a general-purpose programming language that reads almost like plain English. It is used for AI, data analysis, automation, web back ends and scripting. You write instructions in a .py file and the Python interpreter runs them line by line. - Python was created by Guido van Rossum and first released in 1991. It is interpreted: there is no separate compile step you run by hand. The interpreter reads your program from top to bottom and runs each line. - Python cares about readability. Blocks of code are marked by indentation instead of curly braces, so well-formatted code is the only kind that runs. - The editor on this page runs real Python 3 inside your browser using Pyodide, which is CPython compiled to WebAssembly. Nothing is sent to a server. Syntax: ```python print("text to show") ``` Example: ```python print("Hello from Python!") print(2 + 3) print("Python" * 3) ``` Output: ```text Hello from Python! 5 PythonPythonPython ``` Common mistake: Python 2 reached end of life in 2020. If a tutorial writes print "hi" without brackets, it is teaching Python 2: find a newer one. In the real world: A finance team gets 40 Excel files every month and copies totals into one sheet by hand. A 20-line Python script does it in two seconds and never mistypes a number. **Q: Is Python good for beginners?** A: Yes. Python has short, readable syntax, so beginners spend their time on ideas rather than punctuation. It is also used in real jobs, so what you learn first stays useful. **Q: Do I need to install Python to start?** A: No. Every lesson here runs real Python in your browser. Install Python from python.org later, when you want to build programs on your own computer. **Q: Is Python still worth learning when AI can write code?** A: Yes. AI tools write a lot of Python, and someone has to read it, test it and fix it. Knowing Python is how you tell good generated code from code that only looks right. #### print() and your first program URL: https://www.msdevbuild.com/python/py-101/print-and-first-program/ print() is the built-in Python function that shows values on the screen. You can pass it several values separated by commas, and it puts a space between them and a new line at the end. The sep and end arguments change those two defaults. - Text must be inside quotes. Single quotes and double quotes work the same: print('hi') and print("hi") both print hi. - When you pass several values, print("Score:", 42) prints them with one space between. Numbers do not need quotes. - sep sets what goes between values and end sets what goes after the last one. By default they are a space and a new line. - Inside a string, \n starts a new line and \t inserts a tab. These are called escape sequences. Syntax: ```python print(value1, value2, ..., sep=" ", end="\n") ``` Example: ```python print("Hello, world!") print("Score:", 42) print("a", "b", "c", sep="-") print("No new line", end=" ") print("...continued") print("Line 1\nLine 2") ``` Output: ```text Hello, world! Score: 42 a-b-c No new line ...continued Line 1 Line 2 ``` Common mistake: Commas add a space for you: print("Total:", 5) shows Total: 5. Do not put your own space inside the quotes as well, or you get two. In the real world: Log files are mostly print-style lines: a time, a level and a message joined by a separator. Changing sep is how you turn the same values into a CSV row. **Q: What is the difference between single and double quotes in Python?** A: There is none for normal strings. Pick one style and stay with it. Use the other kind when your text contains a quote, for example "It's ready". **Q: Why does print need brackets in Python 3?** A: In Python 3, print became a function, and functions are called with parentheses. The bracket-free form print "hi" only worked in Python 2, which reached end of life in 2020. #### Comments URL: https://www.msdevbuild.com/python/py-101/comments/ A comment is text in your code that Python ignores. In Python a comment starts with # and runs to the end of the line. Use comments to explain why code does something, and to switch a line off while you debug. - Everything after # on a line is ignored. A comment can sit on its own line or after code on the same line. - Python has no special multi-line comment. Start each line with #. A string in triple quotes on its own line is ignored too, and when it is the first line of a function it becomes a docstring, the help text for that function. - Good comments say why, not what. # 18% GST is useful. # multiply price by 0.18 repeats the code. Syntax: ```python # a comment on its own line x = 5 # a comment after code ``` Example: ```python # This line is a comment. Python skips it. price = 250 # price in rupees tax = price * 0.18 # 18% GST # print("debug:", tax) print("Total:", price + tax) """ A string on its own like this is also skipped. """ ``` Output: ```text Total: 295.0 ``` Common mistake: Comment code out to switch it off while you test, but delete it before you share. Old commented-out code confuses the next reader. In the real world: When a bug appears, developers often comment out one line at a time to find which one causes it. It is faster than deleting and retyping. **Q: How do I comment multiple lines in Python?** A: Put # at the start of each line. Most editors do it for you: select the lines and press Ctrl+/ (Cmd+/ on a Mac). **Q: Do comments slow down a Python program?** A: No. Comments are thrown away when Python reads the file, before anything runs. ### Module 2: Variables and data types #### Variables URL: https://www.msdevbuild.com/python/py-101/variables/ A variable is a name that points to a value, such as age = 25. You create it by assigning with =, and you can assign a new value at any time. Python works out the type from the value, so you never declare it. - = means assign, not "equals". age = 25 means "make the name age point to 25". - The right side runs first. In age = age + 1, Python reads the current age, adds 1, then points age at the new value. - Names can contain letters, digits and underscores, cannot start with a digit, and are case-sensitive: Age and age are different. Python style is lower case with underscores, called snake_case: total_price. - You cannot use keywords such as if, for or class as names. Syntax: ```python name = value a, b = 1, 2 ``` Example: ```python name = "Alex" age = 25 age = age + 1 city, country = "Chennai", "India" print(name, "is", age) print(city, country) ``` Output: ```text Alex is 26 Chennai India ``` Common mistake: Python works out the right side of = first. That is why count = count + 1 works: it uses the old count to make the new one. In the real world: In a shopping app, cart_total starts at 0 and changes every time an item is added. That running total is just a variable being reassigned. **Q: Do you need to declare variables in Python?** A: No. A variable exists the moment you assign to it. Python works out the type from the value. **Q: Can a Python variable change type?** A: Yes. x = 5 then x = "five" is allowed, because the name just points at a new value. It works, but it makes code harder to follow, so avoid it. **Q: What is snake_case?** A: Lower-case words joined by underscores, such as total_price. It is the naming style recommended for Python variables and functions in PEP 8. #### Data types URL: https://www.msdevbuild.com/python/py-101/data-types/ A data type tells Python what kind of value something is and what you can do with it. The core types are int for whole numbers, float for decimals, str for text, bool for True or False, and None for "no value". type(x) tells you which one you have. - int is a whole number of any size: 42, -7, 10_000_000. float has a decimal point: 3.14, 2.0. - str is text in quotes: "Chennai". bool is True or False, with a capital first letter. - None means "nothing here yet". It is the value of a variable that has been created but not filled. - Floats are stored in binary, so some decimals are approximate: 0.1 + 0.2 prints 0.30000000000000004. For money, use whole paise or cents, or the decimal module. Syntax: ```python type(value) isinstance(value, int) ``` Example: ```python count = 10 price = 99.5 name = "Python" is_active = True nothing = None print(type(count)) print(type(price)) print(type(name)) print(type(is_active)) print(type(nothing)) print(0.1 + 0.2) ``` Output: ```text 0.30000000000000004 ``` Common mistake: When something behaves strangely, add print(type(x)). A huge share of beginner bugs are a str where you expected an int. In the real world: A phone number looks like a number but should be a str: you never add phone numbers, and int would drop a leading zero. **Q: What are the basic data types in Python?** A: int (whole numbers), float (decimals), str (text), bool (True/False) and None. The collection types list, tuple, dict and set build on these. **Q: Why is 0.1 + 0.2 not 0.3 in Python?** A: Floats are stored in binary, and 0.1 cannot be represented exactly in binary, so a tiny error appears. Every language that uses IEEE 754 floats does the same. Use round() for display, or the decimal module for money. #### Type conversion URL: https://www.msdevbuild.com/python/py-101/type-conversion/ Type conversion, also called casting, turns a value into another type with int(), float(), str() or bool(). You need it whenever text must become a number, for example input from a user. int() drops the decimal part instead of rounding. - "5" + "7" joins two strings and gives "57". int("5") + int("7") adds two numbers and gives 12. - int(3.9) is 3. It cuts off the decimal part. Use round(3.9) if you want 4. - int("hello") raises a ValueError because the text is not a number. Converting user input can fail, and later courses show how to handle that. - bool() returns False for 0, 0.0, "", None and empty collections. Everything else is True. Syntax: ```python int(x) float(x) str(x) bool(x) ``` Example: ```python a = "5" b = "7" print(a + b) print(int(a) + int(b)) print(int(3.9)) print(float("2.5") * 2) print(str(100) + " percent") print(bool(0), bool(""), bool("hi")) ``` Output: ```text 57 12 3 5.0 100 percent False False True ``` Common mistake: int() cuts off the decimals, it does not round: int(2.99) is 2. Use round() when you want the nearest whole number. In the real world: A CSV export of orders has quantity "3" and price "19.99" as text. A report that forgets to convert them will join the strings instead of multiplying the numbers. **Q: How do I convert a string to an integer in Python?** A: Use int(), for example int("42") returns 42. If the text might not be a number, check it first or catch ValueError. **Q: Does int() round in Python?** A: No. int() drops the decimal part, so int(2.9) is 2 and int(-2.9) is -2. Use round() to round to the nearest whole number. ### Module 3: Operators #### Arithmetic operators URL: https://www.msdevbuild.com/python/py-101/arithmetic-operators/ Arithmetic operators do maths on numbers: + - * and / work as you expect, // divides and drops the remainder, % gives the remainder, and ** raises to a power. / always returns a float. Python follows the usual order: brackets, powers, then * / // %, then + and -. - 17 / 5 is 3.4. / always gives a float, even 10 / 2 gives 5.0. - 17 // 5 is 3: how many whole times 5 fits in 17. 17 % 5 is 2: what is left over. - n % 2 == 0 is the standard test for an even number. - Python works out 2 + 3 * 4 as 14 because * comes before +. Brackets make the order clear: (2 + 3) * 4 is 20. Syntax: ```python a + b a - b a * b a / b a // b a % b a ** b ``` Example: ```python a = 17 b = 5 print(a + b) print(a - b) print(a * b) print(a / b) print(a // b) print(a % b) print(2 ** 10) print(2 + 3 * 4) print((2 + 3) * 4) ``` Output: ```text 22 12 85 3.4 3 2 1024 14 20 ``` Common mistake: / always gives a float, even 10 / 2 is 5.0. Use // when you need a whole number, like a page count. In the real world: Paging through search results: page_count = (total + per_page - 1) // per_page. With 101 results and 10 per page you get 11 pages. **Q: What is the difference between / and // in Python?** A: / is true division and always returns a float (7 / 2 is 3.5). // is floor division and returns the whole-number part, rounded down (7 // 2 is 3). **Q: What does % mean in Python?** A: For numbers, % is the modulus operator: it returns the remainder after division. 10 % 3 is 1. It is often used to test for even numbers with n % 2 == 0. #### Comparison and logical operators URL: https://www.msdevbuild.com/python/py-101/comparison-and-logical-operators/ Comparison operators such as ==, !=, < and >= compare two values and give True or False. Logical operators combine those results: and needs both sides True, or needs at least one, and not flips the value. They are the building blocks of every if statement. - == checks equality. A single = assigns. Mixing them up is the most common beginner mistake. - and is True only if both sides are True. or is True if at least one side is True. not turns True into False and back. - Python lets you chain comparisons: 10 < age < 30 means 10 < age and age < 30. - Comparing text is case-sensitive: "Yes" == "yes" is False. Syntax: ```python a == b a != b a < b a > b a <= b a >= b x and y x or y not x ``` Example: ```python age = 20 has_ticket = True print(age >= 18) print(age == 21) print(age != 21) print(age >= 18 and has_ticket) print(age < 13 or age > 65) print(not has_ticket) print(10 < age < 30) ``` Output: ```text True False True True False False True ``` Common mistake: = puts a value in a box; == asks whether two values are equal. if x = 5 is a syntax error; you mean if x == 5. In the real world: A delivery app shows "Free delivery" when cart_total >= 499 or is_member. That one line is a comparison joined with or. **Q: What is the difference between = and == in Python?** A: = assigns a value to a variable. == compares two values and returns True or False. if x = 5 is a syntax error; you mean if x == 5. **Q: What is the difference between == and is in Python?** A: == checks whether two values are equal. is checks whether they are the very same object. Use is only for None (x is None) and use == for everything else. ### Module 4: Strings and input #### Strings and f-strings URL: https://www.msdevbuild.com/python/py-101/strings-and-f-strings/ A string is text, stored as a sequence of characters you can index and slice. String methods such as upper(), strip() and replace() return new strings without changing the original. An f-string, written f"Hi {name}", puts values straight into text and can format numbers. - Positions start at 0. s[0] is the first character and s[-1] the last. s[0:6] takes positions 0 to 5; the end position is not included. - Strings cannot be changed in place. s.upper() gives you a new string, so store it: s = s.upper(). - strip() removes spaces from both ends, which is the first thing to do with text a user typed. - In an f-string, anything in {} is worked out and inserted. {price:,.2f} adds thousands separators and two decimal places. Syntax: ```python s[i] s[start:end] len(s) s.upper() s.lower() s.strip() s.replace(old, new) f"text {value} more {number:.2f}" ``` Example: ```python name = " Python Lessons " clean = name.strip() print(clean) print(len(clean)) print(clean.upper()) print(clean[0], clean[-1]) print(clean[0:6]) print(clean.replace("Lessons", "Lab")) price = 1499.5 print(f"{clean} costs ₹{price:,.2f}") ``` Output: ```text Python Lessons 14 PYTHON LESSONS P s Python Python Lab Python Lessons costs ₹1,499.50 ``` Common mistake: String methods never change the original. name.upper() gives you a new string, so write name = name.upper() if you want to keep it. In the real world: Every invoice, receipt and email template fills names and amounts into fixed text. That is an f-string, or the same idea in another language. **Q: What is an f-string in Python?** A: An f-string is a string literal with f before the quote, such as f"Total: {total}". Expressions inside the braces are evaluated and inserted. They were added in Python 3.6 and are the usual way to format text today. **Q: How do I format a number to 2 decimal places in Python?** A: Use an f-string with a format spec: f"{value:.2f}". Add a comma for thousands separators: f"{value:,.2f}" turns 1499.5 into 1,499.50. #### User input and Lab 01: Calculator URL: https://www.msdevbuild.com/python/py-101/user-input/ input() pauses the program, shows a prompt and returns what the user typed, always as a string. To do maths with what the user typed, convert it first with int() or float(). In this editor, type the answers in the Input box before you press Run. - input("Prompt: ") always returns a str, even when the user types 42. - Wrap it to convert: age = int(input("Age: ")). If the user types something that is not a number, int() raises ValueError. - Here, the editor reads answers from the Input box, one line per input() call, so you can test with different values quickly. Syntax: ```python text = input("Prompt: ") number = int(input("Number: ")) ``` Example: ```python name = input("What is your name? ") age = int(input("How old are you? ")) print(f"Hi {name}, next year you will be {age + 1}.") ``` Output: ```text What is your name? Priya How old are you? 29 Hi Priya, next year you will be 30. ``` Common mistake: input() always returns text. Forget int() or float() and "5" + "5" gives "55", not 10. In the real world: Command-line tools ask questions the same way: git asks for a commit message, installers ask for a folder. Under the hood it is input(). **Q: How do I take integer input in Python?** A: Wrap input() in int(): age = int(input("Age: ")). Use float() instead for decimals. **Q: Why does input() return a string?** A: Python cannot know what you plan to do with what the user typed, so it hands you the exact characters as text. Converting is your decision. ### Module 5: Conditions #### if, elif and else URL: https://www.msdevbuild.com/python/py-101/if-elif-else/ An if statement runs a block of code only when its condition is True. elif checks another condition when the ones before it were False, and else runs when none of them were. Python checks from the top and runs only the first branch that matches. - The condition after if is anything that is True or False. A colon ends the line, and the block underneath is indented by four spaces. - elif means "else if". Python tries each condition in order and stops at the first True one. The rest are skipped. - else has no condition. It catches everything that did not match. You can leave it out if nothing should happen. Syntax: ```python if condition: ... elif other_condition: ... else: ... ``` Example: ```python total = 350 if total >= 500: delivery = 0 elif total >= 200: delivery = 40 else: delivery = 80 print("Delivery:", delivery) print("Pay:", total + delivery) ``` Output: ```text Delivery: 40 Pay: 390 ``` Common mistake: Order matters. Put the most specific condition first: if you check score >= 50 before score >= 90, a score of 95 never reaches the 90 branch. In the real world: Banks use the same shape to set interest rates by balance band, and HR systems use it to pick tax slabs. **Q: What is the difference between if and elif in Python?** A: Each if starts a new check that always runs. elif belongs to the if above it and only runs when everything before it in the chain was False. **Q: Does Python have switch statements?** A: Python 3.10 added match/case, which works like a more powerful switch. For simple ranges, if/elif/else is still the usual choice. #### Nested conditions URL: https://www.msdevbuild.com/python/py-101/nested-conditions/ A nested condition is an if inside another if, so the inner check only happens when the outer one is True. It suits decisions that come in stages. When nesting gets deep, combining conditions with and/or is usually clearer. - Each level of nesting adds four more spaces. The inner if only runs when the outer condition is True. - if a: if b: does the same as if a and b: when there is no else for the outer check. The flat version is easier to read. - Keep nesting when the inner branch needs its own else, such as a different message for "has ticket but too young". Syntax: ```python if outer: if inner: ... else: ... ``` Example: ```python has_ticket = True age = 16 if has_ticket: if age >= 18: print("Enjoy the film") else: print("Sorry, this film is 18+") else: print("Please buy a ticket") ``` Output: ```text Sorry, this film is 18+ ``` Common mistake: More than two levels deep is a warning sign. Try returning early, or join the checks with and so the code reads like a sentence. In the real world: Checkout code checks the cart is not empty, then whether the card is valid, then whether there is stock, each step inside the last. **Q: How deep can if statements be nested in Python?** A: There is no practical limit, but more than two or three levels is hard to read. Combine conditions with and/or, or move parts into functions. **Q: Is nested if slower than and?** A: No meaningful difference. Choose whichever is clearer to read. #### match statements URL: https://www.msdevbuild.com/python/py-101/match-statements/ A match statement compares one value against a list of case patterns and runs the first one that fits. It is Python's version of a switch, added in Python 3.10. The case _ pattern catches anything that did not match. - match value: starts the block. Each case pattern: is checked from top to bottom, and only the first match runs. - case "start" | "go": matches either word. The | means "or" inside a pattern. - case _: is the wildcard. It always matches, so it works like else. Syntax: ```python match value: case "a": ... case "b" | "c": ... case _: ... ``` Example: ```python command = "go" match command: case "start" | "go": print("Starting...") case "stop": print("Stopping.") case _: print("Unknown command:", command) ``` Output: ```text Starting... ``` Common mistake: case _: must come last. Anything below it can never run, because _ matches everything. In the real world: Web servers route requests and games handle key presses with exactly this shape: one value, many possible actions. **Q: Is match the same as switch in Python?** A: It does what switch does and more: it can also match the shape of lists, tuples, dictionaries and objects. For plain values it reads like a switch. **Q: Should I use match or if/elif?** A: Use match when you compare one value against many fixed options. Use if/elif for ranges and comparisons like score >= 90. ### Module 6: Loops #### for loops and range() URL: https://www.msdevbuild.com/python/py-101/for-loops-and-range/ A for loop runs a block once for each item in a sequence, such as a list, a string or a range of numbers. range(5) gives 0 to 4, and range(start, stop, step) lets you choose where to start, where to stop and how far to jump. The stop number is never included. - for name in names: takes each item in turn and runs the indented block with name set to it. - range(5) produces 0, 1, 2, 3, 4. range(2, 6) produces 2 to 5. range(0, 10, 2) counts in twos. - A string is a sequence too: for ch in "hi": loops over each character. Syntax: ```python for item in sequence: ... for i in range(start, stop, step): ... ``` Example: ```python fruits = ["apple", "mango", "kiwi"] for fruit in fruits: print("I like", fruit) for n in range(1, 6, 2): print(n) ``` Output: ```text I like apple I like mango I like kiwi 1 3 5 ``` Common mistake: range(1, 10) stops at 9. If you want 1 to 10, write range(1, 11). In the real world: A payroll script loops over every employee and works out each salary. One loop, any number of employees. **Q: How do I loop with an index in Python?** A: Use enumerate: for i, item in enumerate(items): gives you the position and the item together. It is clearer than range(len(items)). **Q: Can range count backwards?** A: Yes, with a negative step: range(5, 0, -1) gives 5, 4, 3, 2, 1. #### while loops URL: https://www.msdevbuild.com/python/py-101/while-loops/ A while loop repeats its block as long as its condition is True, checking before every round. Use it when you do not know in advance how many rounds you need. Something inside the loop must eventually make the condition False, or it runs forever. - Python checks the condition first. If it is True the block runs, then Python checks again. - Usually a variable changes inside the loop, such as count = count + 1, so the condition becomes False one day. - In this editor a loop that never ends is stopped after a few seconds. On your own computer press Ctrl+C. Syntax: ```python while condition: ... ``` Example: ```python savings = 0 months = 0 while savings < 10000: savings = savings + 1500 months = months + 1 print("Months:", months) print("Saved:", savings) ``` Output: ```text Months: 7 Saved: 10500 ``` Common mistake: If a while loop never ends, check that the variable in the condition actually changes inside the loop. In the real world: Download managers retry a failed download while attempts are under 3, then give up and tell you. **Q: When should I use while instead of for in Python?** A: Use for when you loop over a known collection or count. Use while when you stop on a condition and do not know how many rounds it will take. **Q: How do I stop an infinite loop?** A: Press Ctrl+C in a terminal. In code, make sure the condition can become False, or use break when the job is done. #### break, continue and loop else URL: https://www.msdevbuild.com/python/py-101/break-continue-else/ break ends a loop immediately, continue skips the rest of the current round and goes to the next one. A loop can also have an else block, which runs only if the loop finished without hitting break. Together they cover "stop when found" and "skip this one". - break jumps straight out of the nearest loop. Code after the loop runs next. - continue jumps back to the top for the next item, skipping the rest of the block for this one. - for ... else: runs the else block only when the loop ended normally. It is perfect for "not found" messages. Syntax: ```python for item in items: if skip_this: continue if found_it: break else: ... # no break happened ``` Example: ```python orders = [1200, -5, 800, 52000, 300] for amount in orders: if amount < 0: print("Skipping bad value", amount) continue if amount > 50000: print("Big order found:", amount) break else: print("No big order") ``` Output: ```text Skipping bad value -5 Big order found: 52000 ``` Common mistake: The else on a loop is easy to misread: it means "no break happened", not "the loop was empty". In the real world: Log scanners skip blank lines with continue and stop at the first critical error with break. **Q: Does break exit all loops in Python?** A: No, only the innermost loop it is in. To leave nested loops, use a flag, put the loops in a function and return, or restructure the search. **Q: What is for else in Python used for?** A: For searches: the else block runs when the loop finished without break, which means nothing was found. #### Nested loops URL: https://www.msdevbuild.com/python/py-101/nested-loops/ A nested loop is a loop inside another loop: for every round of the outer loop, the inner loop runs all the way through. They are how you work with rows and columns, like tables, grids and game boards. If the outer loop runs 3 times and the inner 4, the inner block runs 12 times. - The inner loop restarts from the beginning on every outer round. - Use different names for the two loop variables, such as row and col. - Build each row inside the inner loop, then print it once the row is complete. Or use print(..., end="") to stay on one line and a plain print() to start the next row. Syntax: ```python for row in rows: for col in cols: ... ``` Example: ```python for row in "AB": line = "" for seat in range(1, 4): line = line + f"{row}{seat} " print(line.strip()) ``` Output: ```text A1 A2 A3 B1 B2 B3 ``` Common mistake: Nested loops multiply work. 1,000 outer rounds times 1,000 inner rounds is a million. Keep inner loops small. In the real world: Spreadsheet tools loop over every row, and inside each row over every column, to find empty cells. **Q: Are nested loops bad in Python?** A: No, they are the right tool for grids. They become slow when both loops are large, because the work multiplies. **Q: How do I break out of two loops at once?** A: Put the loops in a function and return, or set a flag variable and check it in the outer loop. ### Module 7: Functions #### Defining functions URL: https://www.msdevbuild.com/python/py-101/defining-functions/ A function is a named block of code you can run whenever you need it, by calling its name with brackets. You create one with def, a name, brackets and a colon, then an indented body. Functions stop you repeating yourself and make programs easier to read. - def show_banner(): creates the function. The indented lines under it are its body. - show_banner() calls it. Without the brackets you are only naming it, not running it. - Use verbs for names, in snake_case: send_email, print_report. Syntax: ```python def name(): ... name() ``` Example: ```python def show_banner(): print("*********") print("* HELLO *") print("*********") show_banner() print("Welcome back!") show_banner() ``` Output: ```text ********* * HELLO * ********* Welcome back! ********* * HELLO * ********* ``` Common mistake: Defining a function does not run it. If nothing happens, check that you actually called it with brackets: show_banner(). In the real world: Web apps have functions like send_welcome_email() that dozens of features call, so the email looks the same everywhere. **Q: Why use functions in Python?** A: To avoid repeating code, to give a block a meaningful name, and to test pieces of a program on their own. **Q: Can a function call another function?** A: Yes. Most programs are functions calling functions. A function can even call itself, which is called recursion. #### Parameters and return values URL: https://www.msdevbuild.com/python/py-101/parameters-and-return/ Parameters are the names in a function's brackets that receive the values you pass in, called arguments. return sends a value back to whoever called the function, and ends the function. A function without return gives back None. - def area(width, height): declares two parameters. area(4, 3) passes 4 and 3 as arguments. - return width * height ends the function and gives the result back. Store it: room = area(4, 3). - Arguments are matched to parameters by position: the first goes to the first parameter. Syntax: ```python def name(param1, param2): return result value = name(arg1, arg2) ``` Example: ```python def area(width, height): return width * height room = area(4, 3) hall = area(6, 2) print("Room:", room) print("Total:", room + hall) ``` Output: ```text Room: 12 Total: 24 ``` Common mistake: print shows a value on screen; return hands it back to your code. If you need to use the result later, you need return. In the real world: A shipping service has calculate_shipping(weight, distance) that every part of the checkout calls and uses the returned price. **Q: What is the difference between a parameter and an argument?** A: A parameter is the name in the function definition (def f(x):). An argument is the actual value you pass when calling it (f(5)). **Q: Can a Python function return two values?** A: Yes: return a, b returns a tuple, and you can unpack it with x, y = f(). #### Default and keyword arguments URL: https://www.msdevbuild.com/python/py-101/default-and-keyword-arguments/ A default value makes a parameter optional: def greet(name, greeting="Hello"): uses "Hello" unless you pass something else. Keyword arguments name the parameter in the call, such as greet("Asha", greeting="Hi"), so order no longer matters and the call explains itself. - Parameters with defaults must come after those without: def f(a, b=2): is fine, def f(a=1, b): is a syntax error. - Keyword arguments use the parameter name: make_pizza("paneer", size="large"). - Positional arguments must come before keyword arguments in a call. Syntax: ```python def name(required, option="default"): ... name(1) name(1, option="other") ``` Example: ```python def make_pizza(topping, size="medium", crust="regular"): return f"{size} {topping} pizza, {crust} crust" print(make_pizza("paneer")) print(make_pizza("corn", size="large")) print(make_pizza(crust="thin", topping="veg")) ``` Output: ```text medium paneer pizza, regular crust large corn pizza, regular crust medium veg pizza, thin crust ``` Common mistake: Never use a list or dict as a default, like def f(items=[]). Python reuses the same list on every call. Use None and create the list inside. In the real world: print itself has defaults: sep=" " and end="\n". You have been using keyword arguments since your first lesson. **Q: Can I pass arguments in any order in Python?** A: Yes, if you pass them as keyword arguments by name. Positional arguments must follow the order of the parameters. **Q: Why is a mutable default argument a bug?** A: Default values are created once when the function is defined. A default list is shared by every call, so items pile up. Use None and create a new list inside. #### *args and **kwargs URL: https://www.msdevbuild.com/python/py-101/args-and-kwargs/ *args collects any number of extra positional arguments into a tuple, and **kwargs collects any number of keyword arguments into a dictionary. They let one function accept as many inputs as the caller wants. The names args and kwargs are a convention; the * and ** do the work. - def total(*prices): makes prices a tuple of everything passed in. - def profile(**info): makes info a dict: profile(name="Asha", city="Pune") gives {"name": "Asha", "city": "Pune"}. - You can loop over them like any tuple or dict. Syntax: ```python def f(*args, **kwargs): ... ``` Example: ```python def total(*prices): print("Got", len(prices), "prices") return sum(prices) def profile(**info): for key, value in info.items(): print(key, "=", value) print(total(120, 80, 45)) profile(name="Asha", city="Pune") ``` Output: ```text Got 3 prices 245 name = Asha city = Pune ``` Common mistake: Order in a definition: normal parameters, then *args, then keyword-only ones, then **kwargs. In the real world: Python's own print(*objects, sep=" ", end="\n") uses *objects so you can print any number of values. **Q: What does * mean before a parameter in Python?** A: It collects any extra positional arguments into a tuple. In a call, *list does the opposite: it spreads a list into separate arguments. **Q: When should I use **kwargs?** A: When a function passes options through to another function, or accepts settings whose names you cannot list in advance. #### Scope URL: https://www.msdevbuild.com/python/py-101/scope/ Scope is where a variable can be seen. Variables created inside a function are local: they exist only while the function runs. Variables created outside are global; functions can read them, but assigning to the name inside a function creates a new local variable instead. - A variable assigned inside a function is local. It disappears when the function returns. - A function can read a global variable, but x = ... inside the function makes a new local x. - The global keyword lets a function change a global, but it makes code harder to follow. Returning values is cleaner. Syntax: ```python x = 1 # global def f(): y = 2 # local return x + y ``` Example: ```python bonus = 100 def salary(base): total = base + bonus return total pay = salary(5000) print("Pay:", pay) print("Bonus is still", bonus) ``` Output: ```text Pay: 5100 Bonus is still 100 ``` Common mistake: If you need a function to change a value, return the new value and assign it outside: score = add_points(score, 10). Avoid the global keyword. In the real world: Large codebases avoid global variables because any function could change them, making bugs very hard to trace. **Q: What is the LEGB rule in Python?** A: The order Python looks for a name: Local, Enclosing function, Global, Built-in. The first place that has the name wins. **Q: Why is using global bad?** A: Any function could change the value, so bugs are hard to trace. Passing values in and returning them out keeps functions independent and testable. #### Lambda functions URL: https://www.msdevbuild.com/python/py-101/lambda-functions/ A lambda is a small, unnamed function written in one line: lambda x: x * 2 takes x and returns x * 2. It is used where a short function is needed once, most often as the key for sorted(), max() or min(). For anything longer than one expression, use def. - lambda x: x * 2 is a function that returns x * 2. It has no return keyword; the expression is returned. - sorted(items, key=lambda p: p[1]) sorts by the second element of each item. - A lambda can take several parameters: lambda a, b: a + b. Syntax: ```python lambda parameters: expression sorted(items, key=lambda item: ...) ``` Example: ```python products = [("pen", 20), ("bag", 450), ("book", 120)] cheap_first = sorted(products, key=lambda p: p[1]) print(cheap_first) priciest = max(products, key=lambda p: p[1]) print("Most expensive:", priciest[0]) ``` Output: ```text [('pen', 20), ('book', 120), ('bag', 450)] Most expensive: bag ``` Common mistake: If you are tempted to give a lambda a name (double = lambda x: x * 2), write a normal def instead. It is clearer and shows up properly in error messages. In the real world: Leaderboards sort players by score with key=lambda p: p.score, often with reverse=True for highest first. **Q: When should I use lambda in Python?** A: For a short, one-off function passed to another function, especially key= in sorted, min and max. Use def for anything you name or reuse. **Q: Is lambda faster than def?** A: No. They create the same kind of function object. The difference is only how you write it. #### Recursion URL: https://www.msdevbuild.com/python/py-101/recursion/ Recursion is when a function calls itself to solve a smaller version of the same problem. Every recursive function needs a base case, the simplest input it answers directly, or it would call itself forever. It suits problems that are naturally nested, like folders inside folders. - The base case answers the simplest input without recursing, for example if n == 0: return 1. - The recursive case calls the function with a smaller input: return n * factorial(n - 1). - Each call waits for the one below it, then finishes in reverse order. Watch it in the scene above. Syntax: ```python def f(n): if base_case: return answer return combine(n, f(smaller_n)) ``` Example: ```python def countdown(n): if n == 0: print("Lift off!") return print(n) countdown(n - 1) countdown(3) ``` Output: ```text 3 2 1 Lift off! ``` Common mistake: Python stops after about 1,000 nested calls with RecursionError. For long counts, a loop is the better tool. In the real world: File explorers, website menus with sub-menus and JSON parsers all walk nested structures recursively. **Q: Is recursion better than loops in Python?** A: Not usually for simple repetition; loops are faster and have no depth limit. Recursion shines for nested, tree-like data. **Q: What is the recursion limit in Python?** A: About 1,000 nested calls by default. sys.getrecursionlimit() shows it. Hitting it raises RecursionError. ### Module 8: Collections #### Lists URL: https://www.msdevbuild.com/python/py-101/lists/ A list is an ordered collection of values in square brackets, such as ["tea", "milk"]. You read items by position starting at 0, and you can add, change and remove items at any time because lists are mutable. len() tells you how many items it holds. - items[0] is the first item and items[-1] the last. items[1:3] slices positions 1 and 2. - append(x) adds to the end, insert(i, x) adds at a position, pop() removes and returns the last item, remove(x) deletes the first matching value. - A list can hold mixed types, but in practice lists usually hold one kind of thing. Syntax: ```python items = [a, b, c] items.append(x) items.pop() ``` Example: ```python cart = ["tea", "milk"] cart.append("bread") cart.insert(0, "sugar") print(cart) last = cart.pop() print("Removed", last) cart.remove("milk") print(cart, len(cart)) ``` Output: ```text ['sugar', 'tea', 'milk', 'bread'] Removed bread ['sugar', 'tea'] 2 ``` Common mistake: list.sort() changes the list and returns None. x = items.sort() sets x to None. Use sorted(items) when you want a new list. In the real world: A music app keeps your queue as a list: songs are appended, the next one is popped from the front, and you can drag one to a new position. **Q: What is the difference between append and extend in Python?** A: append adds one item (even if it is a list, it goes in as one item). extend adds each item of another iterable one by one. **Q: How do I copy a list in Python?** A: Use new = old.copy() or new = old[:]. Writing new = old makes two names for the same list, so changing one changes the other. #### Tuples URL: https://www.msdevbuild.com/python/py-101/tuples/ A tuple is an ordered group of values in round brackets, such as (12.97, 77.59), that cannot be changed after it is made. Use it for things that belong together and should stay fixed, like coordinates or an RGB colour. You read it like a list, but you cannot append, remove or reassign items. - point = (3, 4) makes a tuple. point[0] reads 3. point[0] = 9 raises TypeError. - Tuples can be dictionary keys and set members because they never change; lists cannot. - return name, age in a function returns a tuple, which you can unpack: n, a = get_user(). Syntax: ```python t = (a, b, c) x, y = (3, 4) ``` Example: ```python office = (12.97, 77.59) print("Latitude:", office[0]) lat, lng = office print(lat, lng) try: office[0] = 0 except TypeError as e: print("Cannot change:", e) ``` Output: ```text Latitude: 12.97 12.97 77.59 Cannot change: 'tuple' object does not support item assignment ``` Common mistake: A tuple with one item needs a comma: (5,). Without it, (5) is just the number 5 in brackets. In the real world: Database libraries return each row as a tuple, so the row you read stays exactly as it came from the database. **Q: When should I use a tuple instead of a list?** A: Use a tuple for a fixed group whose size and meaning do not change, like (x, y) or (red, green, blue). Use a list for a growing collection of similar items. **Q: Are tuples faster than lists?** A: Slightly, and they use a little less memory, but choose them for meaning and safety, not speed. #### Sets URL: https://www.msdevbuild.com/python/py-101/sets/ A set is an unordered collection of unique values in curly brackets, such as {"tea", "milk"}. Adding a value that is already there does nothing, so sets are the quickest way to remove duplicates. They also answer "what do these two groups share?" with & (intersection), | (union) and - (difference). - set(["a", "b", "a"]) gives {"a", "b"}. Order is not kept, so you cannot index a set. - x in my_set is very fast even with millions of items. - a & b is items in both, a | b items in either, a - b items in a but not in b. Syntax: ```python s = {a, b} s.add(x) a & b a | b a - b ``` Example: ```python emails = ["a@x.com", "b@x.com", "a@x.com", "c@x.com"] unique = set(emails) print(len(emails), "->", len(unique)) team_a = {"Asha", "Ravi", "Li"} team_b = {"Ravi", "Li", "Sam"} print(sorted(team_a & team_b)) print(sorted(team_a - team_b)) print("Sam" in team_b) ``` Output: ```text 4 -> 3 ['Li', 'Ravi'] ['Asha'] True ``` Common mistake: {} is an empty dictionary, not an empty set. Write set() for an empty set. In the real world: Marketing tools use set difference to find customers who signed up but never bought: signed_up - buyers. **Q: How do I remove duplicates from a list in Python?** A: list(set(items)) removes duplicates but loses the order. To keep order use list(dict.fromkeys(items)). **Q: Why is checking membership in a set faster than a list?** A: Sets use hashing, so Python jumps straight to where a value would be instead of checking every item. #### Dictionaries URL: https://www.msdevbuild.com/python/py-101/dictionaries/ A dictionary stores values under unique keys, written as {"name": "Asha", "age": 29}. You read a value with its key, d["name"], and add or update with d[key] = value. It is the right tool whenever you look things up by a name instead of a position. - Keys are usually strings or numbers and must be unique. Values can be anything, even lists or other dicts. - d[key] = value adds a new key or replaces the old value. - for key, value in d.items(): loops over both. d.keys() and d.values() give each side. Syntax: ```python d = {key: value} d[key] = value d.get(key, default) ``` Example: ```python stock = {"tea": 12, "milk": 5} stock["bread"] = 8 stock["milk"] = stock["milk"] - 2 print(stock) print("Coffee:", stock.get("coffee", 0)) for item, qty in stock.items(): print(item, qty) ``` Output: ```text {'tea': 12, 'milk': 3, 'bread': 8} Coffee: 0 tea 12 milk 3 bread 8 ``` Common mistake: d["missing"] raises KeyError. d.get("missing", 0) returns 0 instead, which is perfect for counting. In the real world: Every web API response you read in Python (weather, payments, maps) arrives as JSON and becomes a dictionary. **Q: Are Python dictionaries ordered?** A: Yes. Since Python 3.7 dictionaries keep the order in which keys were added. **Q: How do I check if a key exists in a dictionary?** A: Use if key in d:. It checks keys, not values. #### Comprehensions URL: https://www.msdevbuild.com/python/py-101/comprehensions/ A comprehension builds a new list, dict or set from another collection in one line: [x * 2 for x in nums]. Add if at the end to keep only some items: [x for x in nums if x > 0]. It replaces the common pattern of an empty list, a loop and append. - [expression for item in iterable] runs expression for each item and collects the results. - [x for x in nums if x % 2 == 0] keeps only the items where the condition is True. - {k: v for k, v in pairs} builds a dict; {x for x in items} builds a set. Syntax: ```python [expr for x in items if condition] {key: value for x in items} ``` Example: ```python prices = [100, 250, 40] with_tax = [round(p * 1.18) for p in prices] print(with_tax) cheap = [p for p in prices if p < 200] print(cheap) squares = {n: n * n for n in range(1, 4)} print(squares) ``` Output: ```text [118, 295, 47] [100, 40] {1: 1, 2: 4, 3: 9} ``` Common mistake: If a comprehension needs more than one if or a nested loop to read, switch back to a normal loop. Clear beats clever. In the real world: Data pipelines clean thousands of rows with lines like emails = [e.strip().lower() for e in raw if "@" in e]. **Q: Are list comprehensions faster than for loops?** A: Usually a little, because the appending happens inside Python itself. Choose them mainly because they are shorter and clearer for simple transformations. **Q: What is a generator expression?** A: The same syntax with round brackets, (x * 2 for x in nums). It produces values one at a time instead of building the whole list, which saves memory. #### Unpacking URL: https://www.msdevbuild.com/python/py-101/unpacking/ Unpacking assigns the items of a sequence to several variables at once: name, age = ("Asha", 29). A starred name collects whatever is left, as in first, *rest = scores. It is how Python swaps values, loops over pairs and reads several return values neatly. - a, b = b, a swaps two values in one line. - first, *middle, last = [1, 2, 3, 4] gives first=1, middle=[2, 3], last=4. - for i, name in enumerate(names): and for a, b in zip(list1, list2): both unpack pairs in the loop. Syntax: ```python a, b = pair first, *rest = items for i, x in enumerate(items): ... ``` Example: ```python name, city = ("Asha", "Pune") print(name, "lives in", city) first, *rest = [90, 85, 70, 60] print(first, rest) for place, runner in enumerate(["Li", "Sam"], start=1): print(place, runner) for item, price in zip(["tea", "milk"], [40, 30]): print(item, price) ``` Output: ```text Asha lives in Pune 90 [85, 70, 60] 1 Li 2 Sam tea 40 milk 30 ``` Common mistake: The number of names must match the number of items, unless one name has a star. Otherwise you get "too many values to unpack". In the real world: Reading a CSV row as id, name, email = row makes the next 20 lines of code readable instead of full of row[2]. **Q: What does the star mean in a, *b = items?** A: It collects all remaining items into a list. Only one name per assignment can have a star. **Q: What happens when zip lists have different lengths?** A: zip stops at the shortest list. Use itertools.zip_longest to keep going and fill the gaps. #### Sorting and searching URL: https://www.msdevbuild.com/python/py-101/sorting-and-searching/ sorted(items) returns a new sorted list, while items.sort() sorts the list in place. Both take reverse=True and a key function for custom order, such as key=len. To search, use in to check membership, index() to find a position and min() or max() to pick the extremes. - sorted(nums, reverse=True) sorts high to low. sorted(words, key=len) sorts by length. - Strings sort alphabetically, with capital letters before lower case. Use key=str.lower to ignore case. - items.count(x) counts matches; min() and max() also accept a key. Syntax: ```python sorted(items, key=..., reverse=True) items.sort() x in items items.index(x) ``` Example: ```python scores = [72, 95, 88, 61, 95] top = sorted(scores, reverse=True) print("Top 3:", top[:3]) print("95 appears", scores.count(95), "times") print("88 is at position", scores.index(88)) print("Lowest:", min(scores)) print(sorted(["kiwi", "Apple", "fig"], key=str.lower)) ``` Output: ```text Top 3: [95, 95, 88] 95 appears 2 times 88 is at position 2 Lowest: 61 ['Apple', 'fig', 'kiwi'] ``` Common mistake: items.index(x) raises ValueError when x is missing. Check if x in items first. In the real world: Online shops sort products by price, rating or newest with exactly this: sorted(products, key=lambda p: p["price"]). **Q: How do I sort a list of dictionaries in Python?** A: Pass a key: sorted(rows, key=lambda r: r["price"]). Add reverse=True for highest first. **Q: Is Python sorting stable?** A: Yes. Items that compare equal keep their original order, so you can sort by one key and then another. ### Module 9: Strings in depth #### String methods URL: https://www.msdevbuild.com/python/py-101/string-methods/ String methods are built-in tools you call on any string with a dot, such as text.split() or name.startswith("Dr"). They clean, search and reshape text, and they always return a new string or value because strings never change. split() turns text into a list and join() turns a list back into text. - text.split(",") cuts text at every comma into a list; ", ".join(items) glues a list back together. - find(x) returns the position of x, or -1 if missing. startswith and endswith return True or False. - isdigit() is True when every character is a digit, handy for checking a phone number or PIN. Syntax: ```python text.split(sep) sep.join(items) text.find(x) text.startswith(x) text.count(x) ``` Example: ```python raw = " ASHA@Mail.COM " email = raw.strip().lower() print(email, "@" in email) csv_line = "tea,milk,bread" items = csv_line.split(",") print(items) print(" | ".join(items)) print("Report.pdf".endswith(".pdf"), "2026".isdigit()) ``` Output: ```text asha@mail.com True ['tea', 'milk', 'bread'] tea | milk | bread True True ``` Common mistake: "a,b,,c".split(",") keeps empty pieces. " a b ".split() with no argument splits on any run of spaces and drops the empties. In the real world: Log analysis scripts split each line on spaces to pull out the time, the level and the message. **Q: How do I split a string into words in Python?** A: Use text.split() with no argument. It splits on any whitespace and ignores extra spaces. **Q: How do I join a list of numbers into a string?** A: Convert them first: ", ".join(str(n) for n in nums). join only accepts strings. #### Formatting numbers and dates URL: https://www.msdevbuild.com/python/py-101/formatting-numbers-and-dates/ Inside an f-string, a colon after a value adds a format spec: f"{price:,.2f}" gives 1,499.50 and f"{rate:.1%}" gives 12.5%. Dates use the datetime module and strftime codes such as %d %b %Y for 01 Dec 2026. Formatting changes how a value looks, never the value itself. - .2f means two decimal places; , adds thousands separators; % multiplies by 100 and adds a percent sign. - {name:<10} pads to 10 characters left-aligned, > right-aligns, ^ centres. Great for tidy tables. - date(2026, 12, 1).strftime("%d %b %Y") formats a date. %A is the weekday name. Syntax: ```python f"{value:,.2f}" f"{ratio:.1%}" f"{text:>8}" date.strftime("%d %b %Y") ``` Example: ```python from datetime import date price = 1499.5 rate = 0.125 print(f"Total: ₹{price:,.2f}") print(f"Discount: {rate:.1%}") for item, cost in [("Tea", 40), ("Biscuits", 120)]: print(f"{item:<10}{cost:>6}") bill_day = date(2026, 12, 1) print(bill_day.strftime("%d %b %Y, %A")) ``` Output: ```text Total: ₹1,499.50 Discount: 12.5% Tea 40 Biscuits 120 01 Dec 2026, Tuesday ``` Common mistake: Format only when you display. Keep the real number for calculations, or rounding errors creep in when you turn text back into numbers. In the real world: Banking apps format every amount with separators and two decimals, and every statement line with a readable date. **Q: How do I format a number as currency in Python?** A: Use an f-string with a separator and two decimals: f"₹{amount:,.2f}". For locale-aware formats (like lakhs) use the babel library. **Q: How do I get today's date as text in Python?** A: from datetime import date, then date.today().strftime("%d %b %Y"). #### Slicing patterns URL: https://www.msdevbuild.com/python/py-101/slicing-patterns/ A slice takes part of a string or list with [start:stop:step]. Any part can be left out: s[:3] is the first three, s[-4:] the last four, s[::2] every second item and s[::-1] the whole thing reversed. Slicing never raises an error for out-of-range positions; it just returns what exists. - start is included, stop is not. Missing start means the beginning; missing stop means the end. - Negative numbers count from the end: s[-3:] is the last three characters. - A negative step walks backwards, so s[::-1] reverses. Syntax: ```python s[start:stop:step] s[:n] s[-n:] s[::2] s[::-1] ``` Example: ```python card = "4111222233334242" print("*" * (len(card) - 4) + card[-4:]) word = "Python" print(word[:3], word[3:], word[::2], word[::-1]) days = list(range(1, 11)) print("Last 3:", days[-3:]) print("Page 2:", days[5:10]) ``` Output: ```text ************4242 Pyt hon Pto nohtyP Last 3: [8, 9, 10] Page 2: [6, 7, 8, 9, 10] ``` Common mistake: Slices copy. backup = items[:] gives you a new list, so changing backup does not change items. In the real world: Paging through search results is a slice: items[(page - 1) * size : page * size]. **Q: How do I reverse a string in Python?** A: Use a slice with step -1: text[::-1]. For a list you can also call items.reverse() to reverse it in place. **Q: Why does slicing not raise IndexError?** A: Slices are clamped to the sequence length, so they return whatever part exists. Single-item indexing like s[10] does raise IndexError. #### Regular expressions basics URL: https://www.msdevbuild.com/python/py-101/regular-expressions-basics/ A regular expression is a pattern that describes text, like \d+ for "one or more digits". Python's re module uses it to search: re.findall(pattern, text) returns every match, re.search finds the first, and re.sub replaces matches. Write patterns as raw strings, r"...", so backslashes stay as typed. - \d is a digit, \w a letter, digit or underscore, \s a space. + means one or more, * zero or more. - re.findall(r"\d+", text) returns a list of every match as strings. - re.sub(r"\d", "#", text) replaces every digit with #. Syntax: ```python import re re.findall(r"pattern", text) re.search(r"pattern", text) re.sub(r"pattern", replacement, text) ``` Example: ```python import re msg = "Hi, orders ORD-1042 and ORD-77 are late. Call 98765 43210." print(re.findall(r"ORD-\d+", msg)) first = re.search(r"\d+", msg) print("First number:", first.group()) print(re.sub(r"\d", "#", "PIN 4821")) ``` Output: ```text ['ORD-1042', 'ORD-77'] First number: 1042 PIN #### ``` Common mistake: Always use raw strings for patterns: r"\d+". Without the r, Python may treat backslashes as its own escape codes. In the real world: Banks mask account numbers in emails and logs with re.sub so only the last digits are ever visible. **Q: When should I use regex instead of string methods?** A: Use string methods for fixed text (startswith, split on a comma). Use regex when the text follows a pattern, like "letters, an @, then a domain". **Q: How do I make a regex ignore case in Python?** A: Pass flags=re.IGNORECASE, for example re.findall(r"python", text, flags=re.IGNORECASE). ### Module 10: Files and errors #### Reading and writing files URL: https://www.msdevbuild.com/python/py-101/reading-and-writing-files/ open(name, mode) opens a file: "w" writes (replacing what was there), "a" appends to the end and "r" reads. Use .write() to save text and .read() or a for loop to read it back. Files hold text, so convert numbers with str() before writing. - with open("notes.txt", "w") as f: f.write("text\n") creates or replaces the file. \n ends a line. - with open("notes.txt") as f: text = f.read() reads it all. for line in f: reads one line at a time. - In this course the code runs in a private file system inside your browser, so nothing touches your computer. Syntax: ```python with open("file.txt", "w") as f: f.write("text\n") with open("file.txt") as f: for line in f: ... ``` Example: ```python with open("tasks.txt", "w") as f: f.write("Buy milk\n") f.write("Call Ravi\n") with open("tasks.txt", "a") as f: f.write("Learn Python\n") with open("tasks.txt") as f: for number, line in enumerate(f, start=1): print(number, line.strip()) ``` Output: ```text 1 Buy milk 2 Call Ravi 3 Learn Python ``` Common mistake: "w" wipes the file first. If you meant to add, use "a", or you will lose yesterday's data. In the real world: Servers append a line to a log file for every request, and engineers read those logs when something breaks. **Q: What is the difference between read(), readline() and readlines()?** A: read() returns the whole file as one string, readline() the next line, readlines() a list of all lines. Looping with for line in f is the most memory-friendly way. **Q: Why should I specify encoding when opening files?** A: Different computers use different default encodings. open(name, encoding="utf-8") makes sure text like ₹ or é reads the same everywhere. #### with and context managers URL: https://www.msdevbuild.com/python/py-101/with-and-context-managers/ A with statement runs a block of code inside a context manager, which sets something up at the start and always cleans it up at the end, even if an error happens. with open(...) as f: closes the file for you. The same pattern is used for database connections, locks and timers. - When the with block ends (normally or by an exception) the context manager's cleanup runs. - f.closed is False inside the block and True afterwards. - With contextlib.contextmanager, code before yield is the setup and code after it is the cleanup. Syntax: ```python with something() as name: ... ``` Example: ```python from contextlib import contextmanager with open("log.txt", "w") as f: f.write("started\n") print("Inside, closed?", f.closed) print("After, closed?", f.closed) @contextmanager def step(name): print("Start", name) yield print("Done", name) with step("backup"): print("Copying files...") ``` Output: ```text Inside, closed? False After, closed? True Start backup Copying files... Done backup ``` Common mistake: You do not need f.close() inside a with block. It happens automatically when the block ends. In the real world: Database libraries use with to make sure a transaction is committed when all goes well and rolled back when something fails. **Q: Why use with open instead of open and close?** A: with closes the file even if an error happens halfway, and it is shorter. Forgetting close() leaks files. **Q: Can I open two files in one with statement?** A: Yes: with open("in.txt") as src, open("out.txt", "w") as dst:. #### CSV and JSON URL: https://www.msdevbuild.com/python/py-101/csv-and-json/ CSV stores rows and columns as text with commas, like a spreadsheet, and Python's csv module reads and writes it. JSON stores nested data such as dictionaries and lists, and json.dumps / json.loads convert between Python objects and JSON text. Most data you exchange with spreadsheets and web APIs is in one of the two. - csv.writer(f).writerow([...]) writes one row. Open the file with newline="" so rows are not doubled on Windows. - csv.DictReader(f) reads each row as a dict keyed by the header row. - json.dumps(data, indent=2) turns Python into JSON text; json.loads(text) turns it back. Syntax: ```python import csv, json csv.writer(f).writerow(row) for row in csv.DictReader(f): ... json.dumps(obj) json.loads(text) ``` Example: ```python import csv, json with open("sales.csv", "w", newline="") as f: w = csv.writer(f) w.writerow(["item", "qty"]) w.writerow(["tea", 3]) w.writerow(["milk", 5]) with open("sales.csv", newline="") as f: rows = list(csv.DictReader(f)) total = sum(int(r["qty"]) for r in rows) print(rows[0], total) text = json.dumps({"total": total, "items": [r["item"] for r in rows]}) print(text) print(json.loads(text)["items"][1]) ``` Output: ```text {'item': 'tea', 'qty': '3'} 8 {"total": 8, "items": ["tea", "milk"]} milk ``` Common mistake: csv reads every value as text. Convert numbers with int() or float() before doing maths. In the real world: Most "automate my report" scripts read a CSV export, total some columns and send the result as JSON to another system. **Q: What is the difference between json.load and json.loads?** A: json.load reads JSON from a file object; json.loads reads it from a string. Likewise json.dump writes to a file and json.dumps returns a string. **Q: Should I use pandas for CSV files?** A: For quick scripts the csv module is enough. For analysis, filtering and joining large tables, pandas.read_csv is much easier. #### try, except and finally URL: https://www.msdevbuild.com/python/py-101/try-except-finally/ try runs code that might fail; if it raises an exception, the matching except block handles it instead of the program crashing. else runs when nothing failed, and finally always runs, error or not. Catch specific errors such as ValueError, not everything. - except ValueError: catches only ValueError. You can list several: except (ValueError, TypeError):. - except ValueError as e: gives you the error message in e. - else runs only if the try block succeeded; finally always runs, which is ideal for cleanup. Syntax: ```python try: ... except SomeError as e: ... else: ... finally: ... ``` Example: ```python for text in ["12", "twelve", "0"]: try: n = int(text) result = 100 / n except ValueError: print(text, "-> not a number") except ZeroDivisionError: print(text, "-> cannot divide by zero") else: print(text, "->", result) finally: print("checked", text) ``` Output: ```text 12 -> 8.333333333333334 checked 12 twelve -> not a number checked twelve 0 -> cannot divide by zero checked 0 ``` Common mistake: A bare except: catches everything, including typos in your own code, and hides real bugs. Name the errors you expect. In the real world: Payment code wraps the call to the bank in try/except so a timeout shows "please try again" instead of an error page. **Q: What is the difference between an error and an exception in Python?** A: In everyday speech they mean the same thing. Technically, an exception is the object Python raises when something goes wrong, and you can catch it with except. **Q: Should I use try/except or check with if first?** A: Python style often prefers "try it and handle the failure" (EAFP), especially for conversions and files, because the check and the action can drift apart. #### Raising and custom exceptions URL: https://www.msdevbuild.com/python/py-101/raising-and-custom-exceptions/ raise stops a function and signals a problem, such as raise ValueError("amount must be positive"). A custom exception is a small class that inherits from Exception, which lets callers catch your specific problem by name. Raising early with a clear message makes bugs obvious. - raise ValueError("message") creates the error and stops the function immediately. - class InsufficientFunds(Exception): pass defines a new kind of error. - Callers can except InsufficientFunds: to handle exactly that case and let others pass. Syntax: ```python class MyError(Exception): pass raise MyError("what went wrong") ``` Example: ```python class InsufficientFunds(Exception): pass def withdraw(balance, amount): if amount <= 0: raise ValueError(f"amount must be positive, got {amount}") if amount > balance: raise InsufficientFunds(f"balance {balance} is less than {amount}") return balance - amount print(withdraw(2000, 500)) for amount in (5000, -50): try: withdraw(2000, amount) except InsufficientFunds as e: print("Refused:", e) except ValueError as e: print("Invalid:", e) ``` Output: ```text 1500 Refused: balance 2000 is less than 5000 Invalid: amount must be positive, got -50 ``` Common mistake: Raise with a helpful message that says what went wrong and what was expected: "amount must be positive, got -50". In the real world: Web frameworks define exceptions like NotFound and PermissionDenied; raising one anywhere turns into the right error page. **Q: How do I create a custom exception in Python?** A: Define a class that inherits from Exception: class PaymentFailed(Exception): pass. Raise it with raise PaymentFailed("reason"). **Q: Should I raise or return an error value?** A: Raise. Error values are easy to ignore by accident; exceptions stop the program unless someone deliberately handles them. ### Module 11: Modules and packages #### import and from URL: https://www.msdevbuild.com/python/py-101/import-and-from/ import brings a module into your program, and you use its contents with a dot: import math, then math.sqrt(16). from math import sqrt imports one name so you can call sqrt directly, and as gives a module a shorter nickname. Modules let you reuse code instead of writing everything yourself. - import math then math.pi keeps the module name, so it is obvious where pi came from. - from statistics import mean, median imports just those two names. - import datetime as dt lets you write dt.date instead of the full name. pandas is almost always import pandas as pd. Syntax: ```python import module from module import name import module as short ``` Example: ```python import math from statistics import mean, median import datetime as dt print(math.sqrt(16), round(math.pi, 2)) marks = [72, 90, 85, 64] print("Mean:", mean(marks), "Median:", median(marks)) print(dt.date(2026, 12, 1).isoformat()) ``` Output: ```text 4.0 3.14 Mean: 77.75 Median: 78.5 2026-12-01 ``` Common mistake: Avoid from module import *. It dumps every name into your program and you can no longer tell where something came from. In the real world: A typical data script starts with import pandas as pd, import numpy as np and import matplotlib.pyplot as plt. **Q: What is the difference between a module and a package in Python?** A: A module is one .py file. A package is a folder of modules (traditionally with an __init__.py) that you import as a group, such as email or json. **Q: Where does Python look for modules?** A: In the folder of the running script, then the standard library, then installed packages. sys.path lists the exact folders. #### The standard library tour URL: https://www.msdevbuild.com/python/py-101/standard-library-tour/ The standard library is the large set of modules that comes with Python, so you can use them without installing anything. Everyday favourites include datetime for dates, collections for Counter and defaultdict, pathlib for file paths, random, json, csv and itertools. Check it before writing a tool yourself. - Counter(words).most_common(2) returns the two most frequent items with their counts. - date + timedelta(days=30) does date maths, including month ends and leap years. - Path("reports") / "2026" / "dec.csv" builds file paths that work on every operating system. Syntax: ```python from collections import Counter, defaultdict from datetime import date, timedelta from pathlib import Path ``` Example: ```python from collections import Counter from datetime import date, timedelta from pathlib import Path votes = ["tea", "coffee", "tea", "juice", "tea", "coffee"] print(Counter(votes).most_common(2)) due = date(2026, 12, 1) + timedelta(days=45) print("Due:", due) report = Path("reports") / "2026" / "dec.csv" print(report.name, report.suffix, report.parent.name) ``` Output: ```text [('tea', 3), ('coffee', 2)] Due: 2027-01-15 dec.csv .csv 2026 ``` Common mistake: Python's motto is "batteries included". Search docs.python.org/3/library before pip installing something. In the real world: Billing systems compute due dates with timedelta, and analytics scripts count events with Counter before reaching for bigger libraries. **Q: What does "batteries included" mean in Python?** A: That Python ships with a large standard library for common jobs (files, dates, JSON, maths, networking), so you can do a lot without installing anything. **Q: What is the difference between the standard library and PyPI?** A: The standard library comes with Python. PyPI is the public index of extra packages, such as pandas or requests, that you install with pip. #### pip and virtual environments URL: https://www.msdevbuild.com/python/py-101/pip-and-virtual-environments/ pip installs packages from PyPI, such as pip install requests. A virtual environment, made with python -m venv .venv, is a private folder of packages for one project, so projects never fight over versions. requirements.txt lists a project's packages so anyone can recreate it with pip install -r requirements.txt. - Create: python -m venv .venv. Activate: source .venv/bin/activate (macOS/Linux) or .venv\Scripts\activate (Windows). - Install: pip install requests==2.32.3. Save: pip freeze > requirements.txt. - This browser editor cannot run pip, but the MSDEVBUILD Python playground can import numpy, pandas and matplotlib directly. Syntax: ```python python -m venv .venv source .venv/bin/activate pip install requests pip install -r requirements.txt ``` Example: ```python requirements = """requests==2.32.3 pandas>=2.2 # comment lines are ignored pytest """ for line in requirements.splitlines(): line = line.strip() if not line or line.startswith("#"): continue name = line.replace(">=", "==").split("==")[0] print(name) ``` Output: ```text requests pandas pytest ``` Common mistake: Add .venv/ to .gitignore. Commit requirements.txt, never the venv folder itself. In the real world: Cloud deployments (Azure App Service, Docker images) read requirements.txt to install exactly the packages your app needs. **Q: What is the difference between pip and conda?** A: pip installs Python packages from PyPI. conda is a separate package and environment manager popular in data science that can also install non-Python libraries. **Q: Do I need to activate the virtual environment every time?** A: Yes, in each new terminal. Editors like VS Code can select the venv for you automatically. #### if __name__ == "__main__" URL: https://www.msdevbuild.com/python/py-101/name-main-guard/ Every Python file has a built-in variable __name__. It is "__main__" when you run the file directly, and the module's name when another file imports it. Putting start-up code under if __name__ == "__main__": means it runs only when the file is run, not when it is imported. - Run python tools.py and inside it __name__ == "__main__". - import tools from another file sets tools.__name__ to "tools", so the guarded block is skipped. - In this editor your code runs as the main program, so the guarded block runs. Syntax: ```python def main(): ... if __name__ == "__main__": main() ``` Example: ```python def greet(name): return f"Hello, {name}!" def main(): print(greet("Asha")) print("Running as:", __name__) if __name__ == "__main__": main() ``` Output: ```text Hello, Asha! Running as: __main__ ``` Common mistake: Put the guarded code in a main() function and call main() under the guard. It keeps the global scope clean and makes main testable. In the real world: Command-line tools put argument parsing in main(), so their functions can also be imported and tested without running the tool. **Q: Is if __name__ == "__main__" required?** A: No. A script works without it. It matters when the file might be imported, which is most files that grow beyond a few lines. **Q: What does dunder mean in Python?** A: "Double underscore", the names like __name__ and __init__ that Python uses for special meaning. ### Module 12: Object-oriented Python #### Classes and objects URL: https://www.msdevbuild.com/python/py-101/classes-and-objects/ A class is a blueprint that describes a kind of thing, and an object is one actual thing made from that blueprint. You define a class with the class keyword and create objects by calling it like a function, such as Dog(). Each object keeps its own data, so two dogs can have different names. - class Dog: starts a blueprint. rex = Dog() creates an object, also called an instance. - You can attach data to an object with a dot: rex.name = "Rex". Next lesson shows the proper way, __init__. - type(rex) shows the class and isinstance(rex, Dog) checks it. Syntax: ```python class Name: ... obj = Name() ``` Example: ```python class Dog: pass rex = Dog() rex.name = "Rex" bella = Dog() bella.name = "Bella" print(rex.name, bella.name) print(type(rex).__name__, isinstance(bella, Dog)) ``` Output: ```text Rex Bella Dog True ``` Common mistake: Class names use CapitalWords (PascalCase): BankAccount, not bank_account. Objects and variables stay in snake_case. In the real world: In Django every table is a class, and every row you load from the database becomes an object of that class. **Q: What is the difference between a class and an object in Python?** A: A class is the definition, like the plan for a house. An object is one actual house built from the plan. One class can create many objects. **Q: Is everything an object in Python?** A: Yes. Numbers, strings, lists, functions and even classes are objects, which is why they all have methods you call with a dot. #### __init__ and attributes URL: https://www.msdevbuild.com/python/py-101/init-and-attributes/ __init__ is a special method that runs automatically when an object is created, and it sets up the object's attributes. Its first parameter, self, is the object being built, so self.name = name stores the name on that object. After that, obj.name reads it back. - def __init__(self, name, roll): runs when you call Student("Asha", 12). - Python passes the new object as self automatically; you pass only the other arguments. - Attributes can have defaults: def __init__(self, name, marks=None):. Syntax: ```python class Name: def __init__(self, a, b=0): self.a = a self.b = b ``` Example: ```python class Student: def __init__(self, name, roll, marks=0): self.name = name self.roll = roll self.marks = marks asha = Student("Asha", 12, 91) ravi = Student("Ravi", 7) print(asha.name, asha.roll, asha.marks) print(ravi.name, ravi.marks) ravi.marks = 78 print("Updated:", ravi.marks) ``` Output: ```text Asha 12 91 Ravi 0 Updated: 78 ``` Common mistake: Forgetting self. is the classic bug: name = name inside __init__ only creates a local variable that disappears. In the real world: API client libraries take your key and settings in __init__: client = OpenAI(api_key=...), then every call uses self.api_key. **Q: Is __init__ a constructor in Python?** A: It is usually called the constructor. Strictly, __new__ creates the object and __init__ initialises it, but you will almost always only write __init__. **Q: Why is self needed in Python methods?** A: Python passes the object explicitly so methods know which object they are working on. The name self is a convention, but always use it. #### Methods URL: https://www.msdevbuild.com/python/py-101/methods/ A method is a function defined inside a class. It receives the object as self, so it can read and change that object's attributes. You call it with a dot, such as account.deposit(500), which is the same as Account.deposit(account, 500). - Every method's first parameter is self. Use self.balance to read or change this object's balance. - Call methods on the object: acc.deposit(100). Python supplies self. - Methods can call other methods on the same object: self.deposit(x). Syntax: ```python class Name: def method(self, x): self.value += x return self.value ``` Example: ```python class Account: def __init__(self, owner, balance=0): self.owner = owner self.balance = balance def deposit(self, amount): self.balance += amount def withdraw(self, amount): if amount > self.balance: return False self.balance -= amount return True acc = Account("Asha", 1000) acc.deposit(500) print(acc.withdraw(2000), acc.balance) print(acc.withdraw(300), acc.balance) ``` Output: ```text False 1500 True 1200 ``` Common mistake: Methods that change the object usually return nothing; methods that answer a question return a value. Keep those two jobs separate. In the real world: A shopping cart object has add_item, remove_item and total methods. The checkout page only ever talks to the cart through them. **Q: What is the difference between a function and a method in Python?** A: A method is a function that belongs to a class and receives the object as its first argument. You call it on an object with a dot. **Q: What are classmethod and staticmethod?** A: @classmethod receives the class (cls) instead of an object, often used for alternative constructors. @staticmethod receives neither; it is a plain function grouped inside the class. #### Inheritance URL: https://www.msdevbuild.com/python/py-101/inheritance/ Inheritance lets a new class (the child) start from an existing class (the parent) and get all its attributes and methods, written class Child(Parent):. The child can add new methods or override existing ones, and call the parent's version with super(). It avoids copying code between similar classes. - class Manager(Employee): gives Manager everything Employee has. - Defining a method with the same name overrides it. super().__init__(...) runs the parent's version first. - isinstance(m, Employee) is True for a Manager, because a Manager is an Employee. Syntax: ```python class Child(Parent): def __init__(self, a, b): super().__init__(a) self.b = b ``` Example: ```python class Employee: def __init__(self, name, salary): self.name = name self.salary = salary def describe(self): return f"{self.name} earns {self.salary}" class Manager(Employee): def __init__(self, name, salary, team): super().__init__(name, salary) self.team = team def describe(self): return super().describe() + f" and leads {len(self.team)} people" m = Manager("Asha", 90000, ["Ravi", "Li"]) print(m.describe()) print(isinstance(m, Employee)) ``` Output: ```text Asha earns 90000 and leads 2 people True ``` Common mistake: Use inheritance for "is a" relationships (a Manager is an Employee). For "has a" (a Car has an Engine), store one object inside another instead. In the real world: In Django you write class Order(models.Model): and inherit saving, loading and querying without writing any of it. **Q: Does Python support multiple inheritance?** A: Yes: class C(A, B):. Python uses the method resolution order (C.__mro__) to decide which parent's method wins. Keep it simple and use it sparingly. **Q: What is composition vs inheritance?** A: Inheritance: a class is a specialised version of another. Composition: a class holds other objects as attributes. Prefer composition when the relationship is "has a". #### Polymorphism URL: https://www.msdevbuild.com/python/py-101/polymorphism/ Polymorphism means different classes can be used the same way because they share a method name, even though each does its own thing. A loop can call shape.area() on a circle and a square without knowing which is which. Python cares about what an object can do, not what it is ("duck typing"). - Each class defines a method with the same name and parameters, such as pay(self, amount). - Code that uses them just calls method.pay(amount) and does not check the type. - Duck typing: "if it walks like a duck and quacks like a duck", Python treats it as one. No shared parent is required. Syntax: ```python for thing in things: thing.common_method() ``` Example: ```python class Card: def pay(self, amount): return f"Charged {amount} to card" class UPI: def pay(self, amount): return f"Requested {amount} via UPI" class Wallet: def __init__(self, balance): self.balance = balance def pay(self, amount): self.balance -= amount return f"Paid {amount} from wallet, {self.balance} left" for method in [Card(), UPI(), Wallet(500)]: print(method.pay(120)) ``` Output: ```text Charged 120 to card Requested 120 via UPI Paid 120 from wallet, 380 left ``` Common mistake: If an if type(x) == ... chain keeps growing, that is a sign to give each class the same method and let polymorphism choose. In the real world: AI apps can switch between model providers because each client class offers the same generate() method; the rest of the app never changes. **Q: What is duck typing in Python?** A: Using an object based on what it can do rather than what class it is. If it has the method you call, it works. **Q: What are abstract base classes for?** A: abc.ABC with @abstractmethod lets you require that every subclass implements certain methods, so mistakes are caught early. #### Encapsulation URL: https://www.msdevbuild.com/python/py-101/encapsulation/ Encapsulation means an object protects its own data and only lets the outside change it in controlled ways. Python marks internal attributes with a leading underscore, such as self._balance, and @property lets you expose a value that reads like an attribute but runs checks behind the scenes. That way nobody can set a balance to -500 by accident. - self._balance means "internal, use the methods". It is a convention every Python developer recognises. - @property def balance(self): lets callers write acc.balance (no brackets) to read it. - @balance.setter runs when someone writes acc.balance = x, so you can reject bad values. Syntax: ```python class Name: @property def value(self): return self._value @value.setter def value(self, v): ... self._value = v ``` Example: ```python class Thermostat: def __init__(self, temp): self._temp = temp @property def temp(self): return self._temp @temp.setter def temp(self, value): if not 10 <= value <= 30: raise ValueError("temperature must be 10-30") self._temp = value t = Thermostat(22) t.temp = 25 print(t.temp) try: t.temp = 99 except ValueError as e: print("Rejected:", e) print(t.temp) ``` Output: ```text 25 Rejected: temperature must be 10-30 25 ``` Common mistake: Python does not truly lock attributes; the underscore is a polite "please do not touch". Respect it, and add @property when rules matter. In the real world: Libraries keep their internals in _underscore attributes, so they can change them freely between versions without breaking your code. **Q: Does Python have private variables?** A: Not truly. A single underscore means internal by convention. A double underscore (__x) triggers name mangling, which makes accidental access harder but not impossible. **Q: When should I use @property?** A: When reading or setting a value needs logic (validation, conversion, or computing it from other data) but you want callers to use simple attribute syntax. #### Dunder methods URL: https://www.msdevbuild.com/python/py-101/dunder-methods/ Dunder methods are special methods with double underscores, like __str__ or __eq__, that Python calls for you in certain situations. Define __str__ and print(obj) shows something readable; define __eq__ and == compares your objects; define __len__ and len(obj) works. They make your own classes behave like built-in types. - print(obj) and str(obj) call __str__; the console and lists show __repr__. - a == b calls a.__eq__(b); a < b calls __lt__, which also makes sorted() work. - len(obj) calls __len__; a + b calls __add__. Syntax: ```python def __str__(self): ... def __eq__(self, other): ... def __len__(self): ... ``` Example: ```python class Money: def __init__(self, amount): self.amount = amount def __str__(self): return f"₹{self.amount:,}" def __repr__(self): return f"Money({self.amount})" def __add__(self, other): return Money(self.amount + other.amount) def __eq__(self, other): return self.amount == other.amount def __lt__(self, other): return self.amount < other.amount a, b = Money(1500), Money(250) print(a + b) print(a == Money(1500)) print(sorted([a, b, Money(900)])) ``` Output: ```text ₹1,750 True [Money(250), Money(900), Money(1500)] ``` Common mistake: __repr__ is for developers (unambiguous, ideally looks like code); __str__ is for users (friendly). If you write only one, write __repr__. In the real world: pandas DataFrames print as neat tables and support + and == column by column, all through dunder methods. **Q: What is the difference between __str__ and __repr__?** A: __str__ is the friendly text for users (print). __repr__ is the precise text for developers (console, lists, logs). If __str__ is missing, Python uses __repr__. **Q: Why are they called magic methods?** A: Because Python calls them for you behind operators and built-ins like +, == and len(). "Dunder methods" is the more common name today. #### Dataclasses URL: https://www.msdevbuild.com/python/py-101/dataclasses/ A dataclass is a class mainly for holding data, created with the @dataclass decorator. You list the fields with type hints, and Python writes __init__, __repr__ and __eq__ for you. Options like frozen=True (cannot change) and order=True (can sort) add more with one word. - @dataclass class Point: x: int; y: int gives you Point(1, 2), a readable repr and == that compares fields. - Defaults work like functions: qty: int = 1. Mutable defaults need field(default_factory=list). - @dataclass(frozen=True) makes objects read-only; order=True adds <, > so they sort by their fields. Syntax: ```python from dataclasses import dataclass, field @dataclass class Name: a: int b: str = "x" ``` Example: ```python from dataclasses import dataclass, field @dataclass class Product: name: str price: float qty: int = 1 tags: list[str] = field(default_factory=list) def total(self): return self.price * self.qty pen = Product("Pen", 20.0, 3) print(pen) print(pen.total(), pen == Product("Pen", 20.0, 3)) @dataclass(frozen=True, order=True) class Version: major: int minor: int print(sorted([Version(2, 1), Version(1, 9), Version(2, 0)])) ``` Output: ```text Product(name='Pen', price=20.0, qty=3, tags=[]) 60.0 True [Version(major=1, minor=9), Version(major=2, minor=0), Version(major=2, minor=1)] ``` Common mistake: Never write items: list = [] in a dataclass. Use items: list = field(default_factory=list) so each object gets its own list. In the real world: FastAPI and Pydantic models look just like dataclasses: typed fields that validate incoming JSON automatically. **Q: When should I use a dataclass instead of a normal class?** A: When the class mainly holds data. You still can add methods. For classes that are mostly behaviour with little data, a normal class is fine. **Q: What is the difference between dataclasses and Pydantic?** A: Dataclasses (standard library) generate methods but do not validate types at run time. Pydantic models validate and convert data, which suits API input. ### Module 13: Advanced Python #### Iterators URL: https://www.msdevbuild.com/python/py-101/iterators/ An iterable is anything you can loop over, such as a list or a string. Calling iter() on it gives an iterator, an object that hands out one item each time you call next() and raises StopIteration when it runs out. Every for loop does exactly this behind the scenes. - it = iter([1, 2]), then next(it) gives 1, then 2, then raises StopIteration. - A for loop calls iter() once and next() each round, stopping quietly at StopIteration. - A class becomes an iterator by defining __iter__ (return self) and __next__. Syntax: ```python it = iter(iterable) next(it) ``` Example: ```python it = iter(["red", "amber", "green"]) print(next(it)) print(next(it)) print(next(it)) try: next(it) except StopIteration: print("No more lights") class Countdown: def __init__(self, start): self.n = start def __iter__(self): return self def __next__(self): if self.n == 0: raise StopIteration self.n -= 1 return self.n + 1 print(list(Countdown(3))) ``` Output: ```text red amber green No more lights [3, 2, 1] ``` Common mistake: An iterator is used up once you loop through it. Loop again and you get nothing. Make a fresh one with iter() if you need another pass. In the real world: Database libraries return results as iterators, so a query over millions of rows does not need millions of rows in memory. **Q: What is the difference between an iterable and an iterator?** A: An iterable can produce an iterator (lists, strings, dicts). An iterator remembers its position and gives the next value with next(). Iterators are iterables too. **Q: Why does my zip or map result go empty after one use?** A: zip and map return iterators, which are used up after one pass. Convert to a list if you need it more than once. #### Generators URL: https://www.msdevbuild.com/python/py-101/generators/ A generator is a function that uses yield instead of return. Each time you ask for a value it runs until the next yield, hands that value out and pauses, keeping its place for next time. Generators produce huge or endless sequences without storing them all in memory. - Calling a generator function does not run it; it returns a generator object. - Each next() runs to the next yield. The function's local variables survive between yields. - (x * x for x in range(10)) is a generator expression: like a list comprehension, but lazy. Syntax: ```python def gen(): yield value (expr for x in items) ``` Example: ```python def countdown(n): while n > 0: yield n n -= 1 yield "Lift off!" for value in countdown(3): print(value) squares = (x * x for x in range(1, 6)) print(sum(squares)) ``` Output: ```text 3 2 1 Lift off! 55 ``` Common mistake: Like iterators, a generator is used up after one pass. Call the generator function again to start over. In the real world: AI chat apps stream answers word by word: the model client yields each chunk as it arrives instead of waiting for the full reply. **Q: What is the difference between yield and return?** A: return ends a function and sends back one value. yield sends back a value and pauses, so the function can continue and yield more later. **Q: When should I use a generator instead of a list?** A: When the data is large, endless, or only needed once in order. Use a list when you need indexing, length or several passes. #### Decorators URL: https://www.msdevbuild.com/python/py-101/decorators/ A decorator is a function that takes another function and returns a new function that adds something before or after it, such as logging or a permission check. Writing @my_decorator above def is shorthand for func = my_decorator(func). Frameworks use decorators everywhere, for example @app.get("/") in FastAPI. - Functions are values: you can pass them to other functions and return them. - A decorator defines an inner wrapper(*args, **kwargs) that does extra work and calls the original. - @shout above def greet replaces greet with shout(greet). Syntax: ```python def deco(func): def wrapper(*args, **kwargs): ... return func(*args, **kwargs) return wrapper @deco def f(): ... ``` Example: ```python from functools import wraps def log_calls(func): @wraps(func) def wrapper(*args, **kwargs): print("Calling", func.__name__, args) result = func(*args, **kwargs) print("Returned", result) return result return wrapper @log_calls def add(a, b): return a + b add(2, 3) print(add.__name__) ``` Output: ```text Calling add (2, 3) Returned 5 add ``` Common mistake: Use functools.wraps(func) on your wrapper so the decorated function keeps its real name and docstring. In the real world: FastAPI routes are decorators: @app.get("/users") registers the function underneath as the handler for that URL. **Q: Are decorators only for functions?** A: They can wrap classes too (for example @dataclass). The idea is the same: take something, return an enhanced version. **Q: Can I stack decorators?** A: Yes. Several @ lines stack; the one closest to def is applied first. #### Type hints URL: https://www.msdevbuild.com/python/py-101/type-hints/ Type hints are optional notes that say what type a value should be, such as def total(prices: list[float]) -> float:. Python does not enforce them at run time, but editors and checkers like mypy use them to catch mistakes early and to autocomplete. They also make code easier for people and AI tools to read. - def greet(name: str) -> str: says name is a str and the function returns a str. - list[int], dict[str, float] and tuple[int, int] describe collections. str | None means "a string or None". - Python ignores hints at run time. greet(5) still runs; a checker like mypy reports it. Syntax: ```python def f(x: int, names: list[str]) -> float: ... age: int | None = None ``` Example: ```python def average(marks: list[float]) -> float: return sum(marks) / len(marks) def find_user(users: dict[str, int], name: str) -> int | None: return users.get(name) print(average([72.0, 88.0, 91.0])) print(find_user({"asha": 29}, "asha"), find_user({}, "ravi")) print(average.__annotations__["return"]) ``` Output: ```text 83.66666666666667 29 None ``` Common mistake: Hints are documentation that tools can check. Add them to function signatures first; that is where they help most. In the real world: FastAPI reads your type hints to validate incoming JSON and generate API documentation automatically. **Q: Do type hints make Python faster?** A: No. Standard Python ignores them at run time. They help editors, checkers, documentation and readers. **Q: Should beginners use type hints?** A: Yes on function signatures. They make your intent clear and your editor much more helpful, at very little cost. ### Module 14: Testing and debugging #### Reading tracebacks URL: https://www.msdevbuild.com/python/py-101/reading-tracebacks/ A traceback is the report Python prints when an error stops your program. Read it from the bottom: the last line gives the error type and message, and the lines above show the chain of calls, ending at the exact line that failed. Most bugs are solved by reading that last line carefully. - NameError means a name is not defined (often a typo). TypeError means the wrong type, like "5" + 5. - IndexError means a position past the end; KeyError a missing dictionary key; AttributeError a method the object does not have. - The File "main.py", line N lines show where. The bottom one is where it broke. Syntax: ```python Traceback (most recent call last): File "main.py", line 4, in total = price + qty TypeError: unsupported operand type(s) ... ``` Example: ```python import traceback def get_price(prices, item): return prices[item] try: get_price({"tea": 40}, "coffee") except KeyError as e: print(traceback.format_exc().strip().splitlines()[-1]) last = traceback.extract_tb(e.__traceback__)[-1] print("Failed in:", last.name) ``` Output: ```text KeyError: 'coffee' Failed in: get_price ``` Common mistake: Scroll to the bottom first. The error type (NameError, TypeError, KeyError) already tells you what kind of mistake to look for. In the real world: Production monitoring tools collect tracebacks from crashed requests so engineers can jump straight to the failing line. **Q: What does "most recent call last" mean?** A: The traceback lists calls in order, oldest first. The last entry is the newest call, which is where the error actually happened. **Q: What is the difference between SyntaxError and other errors?** A: A SyntaxError means Python could not even read the code, so nothing ran. Other errors happen while the code is running. #### Debugging step by step URL: https://www.msdevbuild.com/python/py-101/debugging-step-by-step/ Debugging is finding where the program's real behaviour first differs from what you expected. Reproduce the bug, then check values step by step with print() or a debugger (breakpoint() locally, or this course's Watch it scene), until you find the first wrong value. Fix that line, then run the code again to confirm. - Write down what you expected and what actually happened. - Add print(f"{x=}") to see a variable's name and value together. Python 3.8+ supports the = shortcut. - Locally, breakpoint() pauses the program so you can inspect values. Here, the Watch it tab steps through for you. Syntax: ```python print(f"{total=}") breakpoint() # pauses when run locally ``` Example: ```python def apply_discount(total, percent): discount = total * percent / 100 print(f"{total=} {percent=} {discount=}") return total - discount print(apply_discount(500, 10)) print(apply_discount(500, 0.1)) ``` Output: ```text total=500 percent=10 discount=50.0 450.0 total=500 percent=0.1 discount=0.5 499.5 ``` Common mistake: Change one thing at a time and rerun. Changing five things at once means you will not know which one fixed it, or broke something else. In the real world: The second call shows a classic bug: someone passed 0.1 meaning 10%. Printing the values made the mismatch obvious in one run. **Q: Is print debugging bad practice?** A: No. It is quick and effective. Remove the prints when you are done, or use the logging module for messages you want to keep. **Q: How do I use the debugger in VS Code for Python?** A: Click in the margin to set a breakpoint, press F5 to start debugging, then step over lines and watch variables in the side panel. #### assert URL: https://www.msdevbuild.com/python/py-101/assert/ assert condition, "message" checks that a condition is True and raises AssertionError with your message if it is False. It is a quick way to state an assumption in code, and it is the core of how tests check results. Do not use it to validate user input, because asserts can be switched off. - assert total >= 0, "total must not be negative" does nothing when True. - When False it raises AssertionError: total must not be negative. - pytest turns plain asserts into detailed reports showing the values involved. Syntax: ```python assert condition, "message if it fails" ``` Example: ```python def final_price(price, discount): result = price - discount assert result >= 0, f"price went negative: {result}" return result print(final_price(500, 50)) try: final_price(100, 150) except AssertionError as e: print("Caught:", e) ``` Output: ```text 450 Caught: price went negative: -50 ``` Common mistake: Running Python with -O turns asserts off. Use if ... raise ValueError(...) for checks that must always happen, like user input. In the real world: Data pipelines assert that row counts match between steps, so a silent data loss stops the job instead of producing a wrong report. **Q: When should I use assert in Python?** A: To state internal assumptions that should never be false if your code is correct, and in tests. Not for user input or anything that must always be checked. **Q: Why does my assert with brackets always pass?** A: assert (x == 1, "msg") asserts a non-empty tuple, which is always True. Write assert x == 1, "msg" without brackets. #### pytest basics URL: https://www.msdevbuild.com/python/py-101/pytest-basics/ pytest is Python's most popular testing tool: you write functions whose names start with test_, put plain asserts inside, and run pytest to execute them all and report which pass. pytest.raises checks that code raises the right error. Tests let you change code with confidence, because they tell you at once if something broke. - Put tests in files named test_*.py. pytest finds and runs every function starting with test_. - Use plain assert; pytest shows the actual values when one fails. - with pytest.raises(ValueError): passes only if the block raises ValueError. Run everything with pytest in a terminal. Syntax: ```python # test_prices.py def test_adds_tax(): assert add_tax(100) == 118 # terminal pytest ``` Example: ```python def add_tax(amount, rate=18): if amount < 0: raise ValueError("amount must not be negative") return round(amount * (1 + rate / 100), 2) def test_default_rate(): assert add_tax(100) == 118 def test_custom_rate(): assert add_tax(200, rate=5) == 210 def test_negative_amount(): try: add_tax(-1) except ValueError: return raise AssertionError("expected ValueError") tests = [test_default_rate, test_custom_rate, test_negative_amount] for t in tests: t() print("PASSED", t.__name__) print(len(tests), "passed") ``` Output: ```text PASSED test_default_rate PASSED test_custom_rate PASSED test_negative_amount 3 passed ``` Common mistake: Test one behaviour per test, and name it after the behaviour: test_discount_never_goes_below_zero says what failed without reading the code. In the real world: GitHub Actions runs pytest on every pull request, and the merge button stays disabled until every test passes. **Q: What is the difference between unittest and pytest?** A: unittest ships with Python and uses test classes and assertEqual methods. pytest is installed with pip, uses plain functions and asserts, and gives clearer failure messages. Most new projects use pytest. **Q: How many tests should I write?** A: Start with one test per important behaviour, plus one for each bug you fix so it never comes back. ## PY-401 Python Data Science & Analytics URL: https://www.msdevbuild.com/python/py-401/ NumPy, pandas, cleaning messy data, grouping, joining and charts that answer business questions. Every example runs real NumPy and pandas in your browser. Who it is for: Analysts, testers and DBAs moving into data work. ### Module 1: NumPy foundations #### NumPy arrays URL: https://www.msdevbuild.com/python/py-401/numpy-arrays/ A NumPy array is a grid of values that all have the same type, stored side by side in memory so maths on millions of them runs fast. You make one with np.array([...]), and every array knows its shape (rows and columns), ndim (number of dimensions) and dtype (the type of every value). It is the building block under pandas, matplotlib and almost every Python AI library. - Start with import numpy as np. Everyone uses the short name np, so every example you find online matches yours. - np.array([120.0, 80.5]) copies a list into an array. A list of lists becomes a 2-D array: rows and columns. - .shape is a tuple: (4,) is 4 values in a row, (2, 3) is 2 rows of 3. .ndim counts the dimensions. .dtype is the type, such as float64 or int64. - np.zeros((2, 3)) makes a 2 by 3 grid of 0.0, np.arange(0, 10, 2) works like range but returns an array, and np.linspace(0, 1, 5) gives 5 evenly spaced numbers from 0 to 1, end included. Syntax: ```python import numpy as np a = np.array([1.5, 2.0, 3.5]) a.shape, a.ndim, a.dtype np.zeros((rows, cols)) np.arange(start, stop, step) np.linspace(start, stop, count) ``` Example: ```python import numpy as np prices = np.array([120.0, 80.5, 99.9, 45.0]) print(prices) print(prices.dtype, prices.shape, prices.ndim) print(np.zeros((2, 3))) print(np.arange(0, 10, 2)) print(np.linspace(0, 1, 5)) ``` Output: ```text [120. 80.5 99.9 45. ] float64 (4,) 1 [[0. 0. 0.] [0. 0. 0.]] [0 2 4 6 8] [0. 0.25 0.5 0.75 1. ] ``` Common mistake: Every value in an array has the same type. np.array([1, 2, "3"]) quietly turns all three into text. Check .dtype when numbers come from a file. In the real world: A fitness app stores a year of step counts as one array of 365 numbers. The weekly chart, the monthly average and the "best day" badge all come from that one array. **Q: What is the difference between a Python list and a NumPy array?** A: A list can hold mixed types and grow with append. A NumPy array holds one type in a fixed-size block of memory, so maths on every value runs in fast compiled code without a Python loop. **Q: Why is NumPy faster than a Python loop?** A: The loop over the values runs inside NumPy's compiled C code instead of the Python interpreter, and the numbers sit next to each other in memory, so the CPU can process them in bulk. #### Indexing and slicing arrays URL: https://www.msdevbuild.com/python/py-401/array-indexing-and-slicing/ NumPy arrays are indexed with square brackets like lists, but a 2-D array takes a row and a column in one pair: sales[1, 2] is row 1, column 2. A colon means "everything", so sales[:, 0] is the whole first column. Slices give you a view of the same data, not a copy. - Indexes start at 0, and negative indexes count from the end, exactly like lists: a[-1] is the last value. - For 2-D arrays write a[row, col]. a[0] alone is the whole first row. - : means all, so a[:, 2] is column 2 of every row, and a[1:, 1:] is everything from row 1 and column 1 onward. - Slicing does not copy. The slice and the original share memory, which is fast but means writes go through. a[0].copy() makes an independent array. Syntax: ```python a[i] # 1-D: one value a[row, col] # 2-D: one value a[row] # whole row a[:, col] # whole column a[r1:r2, c1:c2] ``` Example: ```python import numpy as np # rows = stores A, B, C columns = Mon, Tue, Wed sales = np.array([[10, 12, 9], [14, 11, 15], [8, 13, 10]]) print(sales[0]) # store A, every day print(sales[1, 2]) # store B on Wednesday print(sales[:, 0]) # Monday, every store print(sales[1:, 1:]) # stores B and C, Tue and Wed ``` Output: ```text [10 12 9] 15 [10 14 8] [[11 15] [13 10]] ``` Common mistake: A slice is a window onto the same numbers. week = sales[0] then week[0] = 99 changes sales too. Use .copy() when you want your own copy. In the real world: An image is a 2-D array of pixels. Cropping a profile photo to a square is one slice: photo[100:400, 200:500]. **Q: What is the difference between a[1][2] and a[1, 2] in NumPy?** A: They return the same value, but a[1, 2] does it in one step. a[1][2] first builds row 1 and then indexes it, which is slower and does not work for column selections like a[:, 2]. **Q: Does slicing a NumPy array copy it?** A: No. A basic slice returns a view that shares memory with the original, so changing the view changes the original. Call .copy() when you need an independent array. #### Vectorised maths and broadcasting URL: https://www.msdevbuild.com/python/py-401/vectorised-maths/ Vectorised maths means writing an operation once and NumPy applies it to every value: prices * qty multiplies matching pairs, and prices * 1.18 multiplies every price by 1.18. Stretching a single number (or a smaller array) to fit a bigger one is called broadcasting. It replaces most for loops in data work and runs far faster. - a + b, a * b, a / b and a ** 2 work value by value when the arrays have the same shape. - With a single number, a * 1.18, NumPy broadcasts the number to every position. - Broadcasting also works between a 2-D table and one row: each row of the table is combined with that row. - Functions such as np.round, np.sqrt and np.abs also run on the whole array. Syntax: ```python a + b # same shape: value by value a * 2 # broadcast one number np.round(a, 2) ``` Example: ```python import numpy as np prices = np.array([100.0, 250.0, 40.0]) qty = np.array([3, 1, 10]) print(prices * qty) # line totals print((prices * qty).sum()) # order total print(prices * 1.18) # every price plus 18% tax celsius = np.array([0, 25, 100]) print(celsius * 9 / 5 + 32) ``` Output: ```text [300. 250. 400.] 950.0 [118. 295. 47.2] [ 32. 77. 212.] ``` Common mistake: Arrays must line up. A shape (3,) array times a shape (4,) array raises "operands could not be broadcast together". Print both .shape values first. In the real world: A weather service turns a whole day of sensor readings from Kelvin to Celsius with one line, readings - 273.15, for thousands of stations at once. **Q: What does vectorised mean in NumPy?** A: It means one expression works on every value of an array, such as prices * 1.18. The loop still happens, but inside NumPy's compiled code instead of a Python for loop, so it is much faster. **Q: What are the broadcasting rules in NumPy?** A: NumPy compares shapes from the right. Two dimensions fit if they are equal or one of them is 1. A single number fits any shape. If any pair does not fit, you get "operands could not be broadcast together". #### Filtering with boolean masks URL: https://www.msdevbuild.com/python/py-401/boolean-masks/ A boolean mask is an array of True and False made by a condition, such as temps > 32. Putting the mask inside square brackets, temps[temps > 32], keeps only the values where the mask is True. Combine conditions with & (and) and | (or), each wrapped in brackets. - temps > 32 compares every value and returns an array of booleans with the same shape. - temps[mask] keeps the values where the mask is True and drops the rest. - True counts as 1, so mask.sum() counts the matches. - np.where(condition, if_true, if_false) builds a new array by choosing per value, for labels such as "hot" and "ok". Syntax: ```python mask = a > 10 a[mask] a[(a > 10) & (a < 20)] np.where(a > 10, "big", "small") ``` Example: ```python import numpy as np temps = np.array([28, 35, 31, 38, 26, 33]) hot = temps > 32 print(hot) print(temps[hot]) print(hot.sum(), "hot days") print(temps[(temps > 27) & (temps < 34)]) print(np.where(temps > 32, "hot", "ok")) ``` Output: ```text [False True False True False True] [35 38 33] 3 hot days [28 31 33] ['ok' 'hot' 'ok' 'hot' 'ok' 'hot'] ``` Common mistake: Use & and |, not and and or, and put brackets around each condition: (a > 1) & (a < 5). Without brackets Python reads it in the wrong order. In the real world: A bank flags card payments with amounts[(amounts > 5000) & (country != home)] and sends only those for a fraud check. **Q: Why does "and" not work with NumPy arrays?** A: and asks for one True or False for the whole array, which NumPy refuses because it is ambiguous. & combines two masks value by value. Wrap each condition in brackets because & binds tighter than >. **Q: How do I find the positions where a condition is true in NumPy?** A: Use np.where(condition) with one argument, or np.flatnonzero(condition) for a 1-D array. Both return the indexes of the True values. #### Aggregations and axes URL: https://www.msdevbuild.com/python/py-401/aggregations-and-axes/ Aggregations reduce many values to one: sum(), mean(), min(), max() and std(). On a 2-D array, axis=0 collapses the rows and gives one result per column, while axis=1 collapses the columns and gives one result per row. argmax() tells you where the biggest value is instead of what it is. - With no axis, a.sum() adds every value in the whole array. - a.sum(axis=0) adds down each column, so the result has one value per column. a.sum(axis=1) adds across each row. - mean, max, min and std take the same axis argument. - argmax returns the index of the largest value. With axis=1 you get, for each row, the column where its best value sits. Syntax: ```python a.sum() # everything a.sum(axis=0) # one per column a.mean(axis=1) # one per row a.argmax(axis=1) # where each row's max is ``` Example: ```python import numpy as np # rows = stores A, B, C columns = Mon, Tue, Wed sales = np.array([[10, 12, 9], [14, 11, 15], [8, 13, 10]]) print(sales.sum()) print(sales.sum(axis=0)) # per day print(sales.sum(axis=1)) # per store print(sales.mean(axis=1).round(1)) print(sales.argmax(axis=1)) # best day of each store ``` Output: ```text 102 [32 36 34] [31 40 31] [10.3 13.3 10.3] [1 2 1] ``` Common mistake: axis is the direction that disappears. axis=0 squashes the rows away (one answer per column); axis=1 squashes the columns away (one answer per row). In the real world: A school report card system stores marks as students × subjects. marks.mean(axis=1) gives each student's average and marks.mean(axis=0) shows which subject the class found hardest. **Q: What does axis=0 mean in NumPy?** A: axis=0 is the rows direction. An aggregation with axis=0 collapses the rows and returns one result per column. axis=1 collapses the columns and returns one result per row. **Q: What is the difference between max and argmax in NumPy?** A: max returns the largest value itself. argmax returns its index, which you use to look up something else, such as the name of the best store or the date of the busiest day. ### Module 2: pandas basics #### pandas Series URL: https://www.msdevbuild.com/python/py-401/pandas-series/ A pandas Series is a single column of values where every value has a label, called the index. It works like a NumPy array, so sales.mean() and sales > 100 run on every value, but you can also read a value by its label, such as sales["Tue"]. Every column of a pandas table is a Series. - Start with import pandas as pd. pandas is built on NumPy, so the maths you learned in module 1 works the same way. - pd.Series([120, 340], index=["Mon", "Tue"]) makes a Series. Without index=, the labels are 0, 1, 2 and so on. - Printing a Series shows the labels on the left, the values on the right and the dtype at the bottom. - sales.mean(), sales * 1.1 and sales[sales > 100] behave like a NumPy array, and the labels travel with the values. Syntax: ```python import pandas as pd s = pd.Series(values, index=labels) s["label"] # by label s.iloc[0] # by position s[s > 100] # filter ``` Example: ```python import pandas as pd sales = pd.Series([120, 340, 95, 410], index=["Mon", "Tue", "Wed", "Thu"]) print(sales) print(sales["Tue"]) print(sales.mean()) print(sales[sales > 100].index.tolist()) ``` Output: ```text Mon 120 Tue 340 Wed 95 Thu 410 dtype: int64 340 241.25 ['Mon', 'Tue', 'Thu'] ``` Common mistake: sales[0] on a Series with text labels is confusing and now warns. Use sales["Mon"] for labels and sales.iloc[0] for positions. In the real world: A stock app keeps a share price as a Series indexed by date, so "the price on 3 March" is prices["2026-03-03"] and a 7-day average is one call. **Q: What is the difference between a pandas Series and a DataFrame?** A: A Series is one column of values with an index. A DataFrame is a table of several Series that share the same index, one Series per column. **Q: What is the difference between a Series and a Python dictionary?** A: Both map labels to values, but a Series keeps its labels in order, holds one type of value and supports vectorised maths and filtering like s > 100, which a dictionary does not. #### pandas DataFrames URL: https://www.msdevbuild.com/python/py-401/pandas-dataframes/ A DataFrame is a table: rows of records and named columns, like a spreadsheet inside Python. You can build one from a dictionary where each key is a column name and each value is a list. Every column is a Series, so staff["salary"].max() works on one column at a time. - pd.DataFrame({"name": [...], "salary": [...]}) builds a table. Keys become column names, lists become columns. - df.shape is (rows, columns). df.columns lists the column names and df.index the row labels. - df["salary"] returns that column as a Series, so .max(), .mean() and .sum() work on it. - df.head() shows the first 5 rows and df.info() shows each column's type and how many values are filled in. Syntax: ```python df = pd.DataFrame({"col": [...], "col2": [...]}) df.shape df.columns df["col"].mean() df.head() ``` Example: ```python import pandas as pd staff = pd.DataFrame({ "name": ["Asha", "Ben", "Chen", "Dina"], "team": ["Data", "Web", "Data", "Ops"], "salary": [72000, 58000, 81000, 64000], }) print(staff) print(staff.shape) print(staff.columns.tolist()) print(staff["salary"].max()) ``` Output: ```text name team salary 0 Asha Data 72000 1 Ben Web 58000 2 Chen Data 81000 3 Dina Ops 64000 (4, 3) ['name', 'team', 'salary'] 81000 ``` Common mistake: Every list in the dictionary must have the same length. If one list is shorter, pandas raises "All arrays must be of the same length". In the real world: A delivery company loads every order of the day into one DataFrame: order id, driver, distance, minutes late. The morning dashboard is built from that table. **Q: How do I create a pandas DataFrame from a dictionary?** A: Pass a dictionary of equal-length lists to pd.DataFrame. Each key becomes a column name and each list becomes that column's values. **Q: How do I see the column types of a DataFrame?** A: Use df.dtypes for the type of each column, or df.info() for the types plus how many non-empty values each column has. #### Reading CSV and Excel files URL: https://www.msdevbuild.com/python/py-401/reading-csv-and-excel/ pd.read_csv("sales.csv") reads a CSV file into a DataFrame, using the first line as column names. pd.read_excel("report.xlsx") does the same for an Excel sheet. Straight after loading, check df.head(), df.shape and df.dtypes so you know what you are working with. - pd.read_csv(path) reads a file. Useful options: sep=";" for semicolon files, usecols=[...] to keep some columns, parse_dates=["date"] to turn text into dates. - The example uses io.StringIO to treat a string as a file, so it runs in the browser without a real file. On your computer, pass a file name instead. - pd.read_excel("report.xlsx", sheet_name="March") reads one sheet. It needs the openpyxl package installed (pip install openpyxl). - After loading, df.head() shows the first rows, df.shape the size and df.dtypes the type pandas picked for each column. Syntax: ```python df = pd.read_csv("sales.csv") df = pd.read_csv("sales.csv", parse_dates=["date"]) df = pd.read_excel("report.xlsx", sheet_name="March") df.head(); df.shape; df.dtypes ``` Example: ```python import io import pandas as pd csv_text = """date,region,product,units,price 2026-01-03,North,Tea,12,2.5 2026-01-03,South,Coffee,7,3.0 2026-01-04,North,Coffee,9,3.0 2026-01-05,East,Tea,15,2.5 2026-01-05,South,Cake,4,4.5 """ df = pd.read_csv(io.StringIO(csv_text)) print(df.head(3)) print(df.shape) print(df.dtypes) ``` Output: ```text date region product units price 0 2026-01-03 North Tea 12 2.5 1 2026-01-03 South Coffee 7 3.0 2 2026-01-04 North Coffee 9 3.0 (5, 5) date object region object product object units int64 price float64 dtype: object ``` Common mistake: Dates load as text (object) unless you ask: pd.read_csv("f.csv", parse_dates=["date"]). Check df.dtypes before doing date maths. In the real world: A bank's fraud team loads the night's card transactions from a CSV export, about 3 million rows, with read_csv and usecols so only the 6 columns they need fill memory. **Q: How do I read only some columns from a CSV in pandas?** A: Pass usecols with the names you want, for example pd.read_csv("sales.csv", usecols=["date", "total"]). The other columns are never loaded, which saves memory on big files. **Q: Why does pandas read_excel fail with "Missing optional dependency openpyxl"?** A: pandas uses the openpyxl package to read .xlsx files and does not install it for you. Run pip install openpyxl in the same environment and try again. #### Selecting rows and columns URL: https://www.msdevbuild.com/python/py-401/selecting-rows-and-columns/ Use df["col"] for one column and df[["a", "b"]] for several. For rows, df.loc[...] selects by label and df.iloc[...] selects by position, and both take a row and a column: df.loc["B1", "price"]. The rule to remember: loc means labels, iloc means integer positions. - df["product"] gives one column as a Series. Double brackets, df[["product", "price"]], give a smaller DataFrame. - df.loc["B1"] is the row labelled B1. df.loc["B1", "price"] is one cell. - df.iloc[0] is the first row whatever its label. df.iloc[0, 1] is row 0, column 1. - Both accept slices and lists: df.loc["A2":"B1", "units"] or df.iloc[:2, [0, 2]]. Syntax: ```python df["col"] # one column df[["a", "b"]] # several columns df.loc[row_label, col_label] df.iloc[row_pos, col_pos] ``` Example: ```python import pandas as pd df = pd.DataFrame({ "product": ["Tea", "Coffee", "Cake", "Juice"], "units": [12, 7, 4, 9], "price": [2.5, 3.0, 4.5, 2.0], }, index=["A1", "A2", "B1", "B2"]) print(df["product"].tolist()) print(df[["product", "price"]]) print(df.loc["B1"]) print(df.iloc[0, 1]) print(df.loc["A2":"B1", "units"].tolist()) ``` Output: ```text ['Tea', 'Coffee', 'Cake', 'Juice'] product price A1 Tea 2.5 A2 Coffee 3.0 B1 Cake 4.5 B2 Juice 2.0 product Cake units 4 price 4.5 Name: B1, dtype: object 12 [7, 4] ``` Common mistake: A loc slice includes the end label ("A2":"B1" keeps B1), but an iloc slice stops before the end position, like normal Python. In the real world: A hotel booking table is indexed by room number. Reception reads one room with bookings.loc[214], while a report takes the 10 most recent rows with bookings.iloc[-10:]. **Q: What is the difference between loc and iloc in pandas?** A: loc selects rows and columns by their labels and includes the end of a slice. iloc selects by integer position and excludes the end of a slice, like normal Python indexing. **Q: Why do I get a SettingWithCopyWarning in pandas?** A: You probably changed a value on a selection made in two steps, such as df[df.x > 1]["y"] = 0, which may change a temporary copy. Do it in one step with df.loc[df.x > 1, "y"] = 0. #### Filtering rows URL: https://www.msdevbuild.com/python/py-401/filtering-rows/ You filter a DataFrame by putting a condition in square brackets: orders[orders["total"] > 400] keeps only the rows where it is True. Combine conditions with & and |, each in brackets, use .isin([...]) to match a list of values, and df.query("total < 350") when you prefer to write the rule as text. It is the same boolean mask idea as in NumPy, applied to whole rows. - orders["total"] > 400 is a True/False Series, one value per row. Putting it in orders[...] keeps the True rows. - The kept rows keep their original index labels, which is why you see 0, 2, 4 in the output. .reset_index(drop=True) renumbers them. - df["city"].isin(["Oslo", "Pune"]) is True when the city is any of the listed values. - df.query("total < 350 and city == 'Leeds'") writes the same filter as a string, which can be easier to read. Syntax: ```python df[df["col"] > 10] df[(df["a"] > 1) & (df["b"] == "x")] df[df["col"].isin(["x", "y"])] df.query("col < 10") ``` Example: ```python import pandas as pd orders = pd.DataFrame({ "customer": ["Asha", "Ben", "Chen", "Dina", "Eli"], "city": ["Pune", "Leeds", "Pune", "Oslo", "Leeds"], "total": [450, 120, 980, 300, 760], }) print(orders[orders["total"] > 400]) print(orders[(orders["city"] == "Leeds") & (orders["total"] > 200)]) print(orders[orders["city"].isin(["Oslo", "Pune"])]["customer"].tolist()) print(orders.query("total < 350").shape[0]) ``` Output: ```text customer city total 0 Asha Pune 450 2 Chen Pune 980 4 Eli Leeds 760 customer city total 4 Eli Leeds 760 ['Asha', 'Chen', 'Dina'] 2 ``` Common mistake: Use & and | with brackets: (df.a > 1) & (df.b == "x"). Writing and raises "The truth value of a Series is ambiguous". In the real world: An online shop sends a "your cart is waiting" email only to carts[(carts["items"] > 0) & (carts["hours_idle"] > 24)], the shoppers who left something behind a day ago. **Q: How do I filter a pandas DataFrame by multiple conditions?** A: Wrap each condition in brackets and join them with & for and, | for or, and ~ for not, for example df[(df.city == "Leeds") & (df.total > 200)]. **Q: What does "The truth value of a Series is ambiguous" mean?** A: You used and, or or if with a whole column. Python needs one True or False, but a column has many. Use & and | between bracketed conditions, or .any() and .all() when you really want one answer. ### Module 3: Cleaning messy data #### Missing values URL: https://www.msdevbuild.com/python/py-401/missing-values/ Missing values are empty cells, which pandas shows as NaN (or None for text). df.isna().sum() counts them per column, df.dropna() removes rows that have any, and df["col"].fillna(value) fills them in. Decide per column: drop the row, fill with a sensible value such as the mean, or mark it as "Unknown". - NaN means "not a number" and marks a missing value. In text columns pandas may show None. isna() finds both. - df.isna().sum() is the first thing to run on a new file: one count per column. - df.dropna() drops every row with any gap. df.dropna(subset=["units"]) only looks at the columns you name. - fillna fills gaps: a fixed value such as 0 or "Unknown", or a statistic such as df["units"].mean(). Assign the result back to the column. Syntax: ```python df.isna().sum() df.dropna(subset=["col"]) df["col"] = df["col"].fillna(value) ``` Example: ```python import numpy as np import pandas as pd sales = pd.DataFrame({ "store": ["Pune", "Leeds", "Oslo", "Lyon"], "units": [12, np.nan, 9, 15], "manager": ["Asha", "Ben", None, "Dina"], }) print(sales.isna().sum()) print(sales.dropna()) sales["units"] = sales["units"].fillna(sales["units"].mean()) sales["manager"] = sales["manager"].fillna("Unknown") print(sales) ``` Output: ```text store 0 units 1 manager 1 dtype: int64 store units manager 0 Pune 12.0 Asha 3 Lyon 15.0 Dina store units manager 0 Pune 12.0 Asha 1 Leeds 12.0 Ben 2 Oslo 9.0 Unknown 3 Lyon 15.0 Dina ``` Common mistake: dropna() with no arguments drops a row if any column is empty, which can throw away most of your data. Use subset=["units"] to drop only rows missing the columns you need. In the real world: A hospital dashboard fills missing heart-rate readings with the patient's previous reading (ffill()) instead of the ward average, because a gap of one minute means "probably unchanged". **Q: Should I drop or fill missing values in pandas?** A: Drop rows when only a few are missing and they are not special. Fill when dropping would lose too much data: use 0 or "Unknown" when that is the true meaning, the mean or median for numbers, or the previous value for readings over time. **Q: What is the difference between NaN and None in pandas?** A: NaN is a floating-point marker for a missing number; None is Python's empty value and often appears in text columns. pandas treats both as missing, so isna, dropna and fillna handle them the same way. #### Fixing types and dates URL: https://www.msdevbuild.com/python/py-401/fixing-types-and-dates/ A column often loads as text (object) even when it holds numbers or dates. pd.to_numeric(col, errors="coerce") turns text into numbers and bad values into NaN, pd.to_datetime(col) turns text into real dates, and col.astype(int) changes a clean column's type. Once a column is a date, .dt gives you the day, month or weekday. - df.dtypes shows each column's type. object usually means text. - Clean text first if needed, for example .str.replace(",", "") to remove thousands separators, then pd.to_numeric(..., errors="coerce"). - pd.to_datetime(col) understands ISO dates like 2026-03-01. For other formats pass format="%d/%m/%Y" so 03/04 is read the way you mean. - col.astype(int) works when every value is already a clean whole number. After conversion, col.dt.day_name(), col.dt.month and col.dt.year read parts of a date. Syntax: ```python pd.to_numeric(df["col"], errors="coerce") pd.to_datetime(df["col"], format="%Y-%m-%d") df["col"].astype(int) df["date"].dt.month ``` Example: ```python import pandas as pd orders = pd.DataFrame({ "order_date": ["2026-03-01", "2026-03-04", "2026-03-09"], "amount": ["1,200", "350", "n/a"], "qty": ["3", "1", "2"], }) print(orders.dtypes) orders["order_date"] = pd.to_datetime(orders["order_date"]) orders["amount"] = pd.to_numeric(orders["amount"].str.replace(",", ""), errors="coerce") orders["qty"] = orders["qty"].astype(int) print(orders.dtypes) print(orders["order_date"].dt.day_name().tolist()) print(orders["amount"].sum()) ``` Output: ```text order_date object amount object qty object dtype: object order_date datetime64[ns] amount float64 qty int64 dtype: object ['Sunday', 'Wednesday', 'Monday'] 1550.0 ``` Common mistake: Use errors="coerce" with to_numeric and to_datetime. Without it, one bad value like "n/a" stops the whole conversion with an error. In the real world: An e-commerce team converts order timestamps with to_datetime and then groups by dt.hour to find out that most orders arrive between 8 and 10 in the evening, so that is when they run promotions. **Q: How do I convert a column to numbers in pandas?** A: Use pd.to_numeric(df["col"], errors="coerce"). Clean symbols such as commas or currency signs first with .str.replace, because those make values unreadable and they become NaN. **Q: How do I read dates like 03/04/2026 correctly in pandas?** A: Pass the format so pandas does not guess: pd.to_datetime(df["date"], format="%d/%m/%Y") for day first, or "%m/%d/%Y" for month first. #### Finding and removing duplicates URL: https://www.msdevbuild.com/python/py-401/duplicates/ Duplicates are rows that appear more than once, often from exporting the same data twice or a form submitted twice. df.duplicated() marks every repeat as True, and df.drop_duplicates() removes them. Use subset=["email"] to compare only some columns, and keep="last" to keep the newest copy instead of the first. - df.duplicated() is True for each row that exactly matches an earlier row in every column. - df.drop_duplicates() keeps the first copy of each and removes the rest. The kept rows keep their index labels. - subset=["email"] compares only that column, so two rows with the same email count as duplicates even if their plan differs. - keep="last" keeps the latest copy, which is usually the most up to date. keep=False drops every copy, including the first. Syntax: ```python df.duplicated() df.drop_duplicates() df.drop_duplicates(subset=["col"], keep="last") ``` Example: ```python import pandas as pd signups = pd.DataFrame({ "email": ["asha@x.com", "ben@x.com", "asha@x.com", "chen@x.com", "ben@x.com"], "plan": ["free", "pro", "free", "free", "team"], }) print(signups.duplicated().tolist()) print(signups.drop_duplicates()) latest = signups.drop_duplicates(subset="email", keep="last") print(latest) ``` Output: ```text [False, False, True, False, False] email plan 0 asha@x.com free 1 ben@x.com pro 3 chen@x.com free 4 ben@x.com team email plan 2 asha@x.com free 3 chen@x.com free 4 ben@x.com team ``` Common mistake: Count before and after: len(df) then len(df.drop_duplicates()). If half your rows vanish, your subset is probably too narrow. In the real world: A CRM merges contacts from a web form and a trade-show scanner. drop_duplicates(subset=["email"], keep="last") keeps one record per person with their latest details. **Q: How do I remove duplicates based on one column in pandas?** A: Use df.drop_duplicates(subset=["column"]). Add keep="last" to keep the most recent row for each value instead of the first. **Q: How do I see the duplicate rows before removing them?** A: Filter with the mask: df[df.duplicated(keep=False)] shows every row that has a twin, including the first copy, so you can check them before deleting anything. #### Cleaning text columns URL: https://www.msdevbuild.com/python/py-401/cleaning-text-columns/ Text columns are cleaned with the .str accessor, which runs a string method on every value: df["name"].str.strip().str.title() removes extra spaces and fixes capitals in one line. .str.replace(r"\D", "", regex=True) removes every non-digit, and .str.contains("Rao") finds matching rows. Clean text before you group or count, or "Pune" and "pune " end up as two cities. - .str gives a column the string methods you know from PY-101: strip, lower, upper, title, replace, startswith and more. - Methods chain: .str.strip().str.lower() removes spaces, then lowers the case. - .str.replace(pattern, "", regex=True) uses a regular expression. \D means "any character that is not a digit". - .str.contains("text") returns True/False per row, so it works as a filter. Add case=False to ignore capitals. Syntax: ```python df["col"].str.strip().str.title() df["col"].str.replace(r"\D", "", regex=True) df[df["col"].str.contains("text", case=False)] ``` Example: ```python import pandas as pd people = pd.DataFrame({ "name": [" asha RAO", "Ben smith ", "CHEN li"], "city": ["pune", "Pune ", "LEEDS"], "phone": ["+91-98450 12345", "(0113) 496 0000", "98450-55555"], }) people["name"] = people["name"].str.strip().str.title() people["city"] = people["city"].str.strip().str.capitalize() people["phone"] = people["phone"].str.replace(r"\D", "", regex=True) print(people) print(people["city"].value_counts().to_dict()) print(people[people["name"].str.contains("Rao")]["name"].tolist()) ``` Output: ```text name city phone 0 Asha Rao Pune 919845012345 1 Ben Smith Pune 01134960000 2 Chen Li Leeds 9845055555 {'Pune': 2, 'Leeds': 1} ['Asha Rao'] ``` Common mistake: .str methods return NaN for missing values instead of crashing, so you can clean first and handle gaps afterwards. In the real world: A delivery company strips and upper-cases every postcode before matching addresses to depots, so "ls1 4ap " and "LS1 4AP" go to the same van. **Q: How do I remove spaces from a pandas column?** A: Use df["col"].str.strip() to remove spaces at both ends. To remove every space, use df["col"].str.replace(" ", ""). **Q: How do I make text lowercase in pandas?** A: Use df["col"].str.lower(). Lowercasing before grouping or joining means "Pune" and "PUNE" match. ### Module 4: Summarising and joining #### groupby: totals per group URL: https://www.msdevbuild.com/python/py-401/groupby/ groupby splits a table into groups that share a value, runs a calculation on each group and puts the results back together. sales.groupby("region")["revenue"].sum() gives one total per region. Use .agg(["sum", "mean", "count"]) for several results at once, and a list of columns to group by two things. - Read df.groupby("region")["revenue"].sum() as: split by region, take the revenue column, add up each group. - Any aggregation works after groupby: sum, mean, count, min, max, median, nunique. - .agg(["sum", "mean", "count"]) returns one column per statistic. Named aggregation, .agg(total=("revenue", "sum")), lets you name the result columns. - groupby(["region", "product"]) makes one group per combination. .reset_index() turns the result back into a flat table. Syntax: ```python df.groupby("key")["col"].sum() df.groupby("key")["col"].agg(["sum", "mean"]) df.groupby(["a", "b"])["col"].sum().reset_index() ``` Example: ```python import pandas as pd sales = pd.DataFrame({ "region": ["North", "South", "North", "East", "South", "North"], "product": ["Tea", "Tea", "Cake", "Tea", "Cake", "Tea"], "revenue": [120, 90, 200, 60, 150, 80], }) print(sales.groupby("region")["revenue"].sum()) print(sales.groupby("region")["revenue"].agg(["sum", "mean", "count"]).round(1)) print(sales.groupby(["region", "product"])["revenue"].sum().reset_index()) ``` Output: ```text region East 60 North 400 South 240 Name: revenue, dtype: int64 sum mean count region East 60 60.0 1 North 400 133.3 3 South 240 120.0 2 region product revenue 0 East Tea 60 1 North Cake 200 2 North Tea 200 3 South Cake 150 4 South Tea 90 ``` Common mistake: The groups become the index of the result. Add .reset_index() to turn them back into a normal column before you save, merge or plot. In the real world: A ride-hailing company runs trips.groupby("driver_id")["rating"].mean() every night and contacts drivers whose average drops below 4.5. **Q: How do I get a DataFrame instead of a Series from pandas groupby?** A: Add .reset_index() to the result, or pass as_index=False to groupby. Both give you a flat table with the group values as a normal column. **Q: What is the difference between count and size in pandas groupby?** A: count gives the number of non-missing values in each column per group. size gives the number of rows per group, including rows with missing values. #### Pivot tables URL: https://www.msdevbuild.com/python/py-401/pivot-tables/ A pivot table turns long data into a grid: one row per value of one column, one column per value of another, and a summary in each cell. df.pivot_table(index="region", columns="month", values="revenue", aggfunc="sum") gives revenue per region per month. pd.crosstab(a, b) is the shortcut for counting how often each pair appears. - index picks the rows, columns picks the columns, values is the number to summarise and aggfunc is how (sum, mean, count). - Combinations with no data are NaN. fill_value=0 shows 0 instead. - margins=True adds an "All" row and column with the totals. - pd.crosstab(df["region"], df["month"]) counts how many rows have each pair, which is handy for "how many orders" questions. Syntax: ```python df.pivot_table(index="rows", columns="cols", values="num", aggfunc="sum", fill_value=0) pd.crosstab(df["a"], df["b"]) ``` Example: ```python import pandas as pd sales = pd.DataFrame({ "month": ["Jan", "Jan", "Feb", "Feb", "Feb", "Mar"], "region": ["North", "South", "North", "South", "North", "South"], "revenue": [120, 90, 200, 150, 80, 60], }) table = sales.pivot_table(index="region", columns="month", values="revenue", aggfunc="sum", fill_value=0) print(table[["Jan", "Feb", "Mar"]]) print(pd.crosstab(sales["region"], sales["month"])[["Jan", "Feb", "Mar"]]) ``` Output: ```text month Jan Feb Mar region North 120 280 0 South 90 150 60 month Jan Feb Mar region North 1 2 0 South 1 1 1 ``` Common mistake: Months sort alphabetically (Feb before Jan). Pick the order you want with table[["Jan", "Feb", "Mar"]], or convert months to real dates first. In the real world: A school builds marks.pivot_table(index="student", columns="subject", values="score") so each teacher sees the whole class on one screen, one student per row. **Q: What is the difference between pivot and pivot_table in pandas?** A: pivot only reshapes and fails if a row and column pair appears twice. pivot_table also summarises duplicates with aggfunc, so it works on raw transaction data. **Q: How do I flatten a pandas pivot table?** A: Call .reset_index() to turn the row labels into a column. If the columns have several levels, join them with table.columns = ["_".join(map(str, c)) for c in table.columns]. #### merge and join URL: https://www.msdevbuild.com/python/py-401/merge-and-join/ merge combines two tables by matching values in a shared column, like a SQL JOIN or an Excel VLOOKUP. orders.merge(customers, on="customer_id") adds each customer's name to their orders. how="inner" (the default) keeps only matches, how="left" keeps every row of the left table, and pd.concat stacks tables on top of each other. - left.merge(right, on="key") matches rows where the key is equal. Use left_on and right_on when the names differ. - how="inner" keeps only keys found in both tables. how="left" keeps every left row and fills NaN where the right table has no match. "right" and "outer" also exist. - An order for customer 30 disappears in an inner join because customer 30 is not in the customer table. A left join keeps it with NaN for the name. - pd.concat([a, b], ignore_index=True) stacks tables with the same columns, such as January and February exports. Syntax: ```python left.merge(right, on="key") left.merge(right, on="key", how="left") pd.concat([a, b], ignore_index=True) ``` Example: ```python import pandas as pd orders = pd.DataFrame({ "order_id": [1, 2, 3, 4], "customer_id": [10, 20, 10, 30], "amount": [250, 90, 120, 400], }) customers = pd.DataFrame({ "customer_id": [10, 20, 40], "name": ["Asha", "Ben", "Dina"], }) print(orders.merge(customers, on="customer_id")) print(orders.merge(customers, on="customer_id", how="left")) ``` Output: ```text order_id customer_id amount name 0 1 10 250 Asha 1 2 20 90 Ben 2 3 10 120 Asha order_id customer_id amount name 0 1 10 250 Asha 1 2 20 90 Ben 2 3 10 120 Asha 3 4 30 400 NaN ``` Common mistake: After a merge, check the row count. If it grew, the key repeats on both sides. validate="many_to_one" makes pandas raise an error instead of silently duplicating rows. In the real world: An online shop merges the orders table with the products table on product_id to get each order's category, then groups by category for the weekly report. **Q: What is the difference between merge and join in pandas?** A: merge joins on columns and is the general tool. join is a shortcut that joins on the index by default. Both can do inner, left, right and outer joins. **Q: How do I merge on columns with different names?** A: Use left_on and right_on, for example orders.merge(customers, left_on="cust", right_on="customer_id"). You can drop the extra key column afterwards. #### apply and map URL: https://www.msdevbuild.com/python/py-401/apply-and-map/ map replaces each value in a column using a dictionary or function, such as turning "D" into "Data". apply runs a function on every value of a column, or on every row with axis=1, for rules that built-in methods cannot express. Prefer plain vectorised maths like df["salary"] / 12 when it works, because it is much faster. - df["team"].map({"D": "Data", "W": "Web"}) looks up each value in the dictionary. - df["salary"].apply(func) calls func with each value. A short lambda is common for one-line rules. - df.apply(func, axis=1) calls func with each whole row, so the function can read several columns: row["name"], row["team"]. - apply runs Python code per value, which is slow on millions of rows. Use vectorised maths, np.where or pd.cut when they fit. Syntax: ```python df["col"].map({"a": "Apple"}) df["col"].apply(lambda x: ...) df.apply(lambda row: ..., axis=1) ``` Example: ```python import pandas as pd staff = pd.DataFrame({ "name": ["Asha", "Ben", "Chen"], "team": ["D", "W", "D"], "salary": [72000, 58000, 81000], }) staff["team"] = staff["team"].map({"D": "Data", "W": "Web"}) staff["band"] = staff["salary"].apply(lambda s: "Senior" if s >= 70000 else "Mid") staff["monthly"] = (staff["salary"] / 12).round() print(staff) print(staff.apply(lambda row: f"{row['name']} ({row['team']})", axis=1).tolist()) ``` Output: ```text name team salary band monthly 0 Asha Data 72000 Senior 6000.0 1 Ben Web 58000 Mid 4833.0 2 Chen Data 81000 Senior 6750.0 ['Asha (Data)', 'Ben (Web)', 'Chen (Data)'] ``` Common mistake: map with a dictionary turns values missing from the dictionary into NaN. Check with .isna().sum() after mapping, or add the missing keys. In the real world: A logistics team maps country codes to regions with a dictionary, then applies a function that sets "express" or "standard" from both the weight and the destination of each parcel. **Q: What is the difference between map and apply in pandas?** A: map works on a Series and is ideal for translating values with a dictionary. apply calls a function on each value of a Series, or on each row or column of a DataFrame with axis. **Q: Why is pandas apply slow?** A: apply calls your Python function once per value or row, so it loses NumPy's compiled speed. Vectorised operations, np.where, np.select and pd.cut do the same jobs much faster on large tables. ### Module 5: Visualisation #### matplotlib basics URL: https://www.msdevbuild.com/python/py-401/matplotlib-basics/ matplotlib is the standard Python library for charts. You create a figure and axes with fig, ax = plt.subplots(), draw on the axes with ax.plot(x, y) or ax.bar(x, y), and label it with ax.set_title, ax.set_xlabel and ax.set_ylabel. pandas, seaborn and most Python chart tools draw with matplotlib underneath. - Import it as import matplotlib.pyplot as plt, the name every example uses. - fig, ax = plt.subplots() gives you a figure (the whole image) and one axes (the chart area). You call drawing methods on ax. - ax.plot(x, y, marker="o") draws a line with dots, ax.bar(x, y) draws bars. Both take lists, arrays or pandas columns. - In this course the chart appears under the output when you press Run. On your computer, plt.show() opens a window and fig.savefig("chart.png") saves a file. Syntax: ```python import matplotlib.pyplot as plt fig, ax = plt.subplots() ax.plot(x, y, marker="o") ax.set_title("..."); ax.set_xlabel("..."); ax.set_ylabel("...") ``` Example: ```python import matplotlib.pyplot as plt months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun"] sales = [120, 135, 150, 98, 160, 175] fig, ax = plt.subplots(figsize=(6, 3)) ax.plot(months, sales, marker="o") ax.set_title("Sales dipped in April, then recovered") ax.set_xlabel("Month") ax.set_ylabel("Sales (units)") worst = months[sales.index(min(sales))] print("Lowest month:", worst) ``` Output: ```text Lowest month: Apr ``` Common mistake: Always label the axes and give the chart a title that says the answer, such as "Sales dipped in April", not just "Sales". In the real world: A website team plots daily visitors every morning. When a line suddenly drops to zero, they know the tracking broke before any report is late. **Q: What is the difference between plt.plot and ax.plot?** A: plt.plot draws on the current axes that pyplot tracks for you. ax.plot draws on a specific axes you created with plt.subplots, which is clearer and works better when a figure has several charts. **Q: Why does my matplotlib chart not show?** A: In a script you need plt.show() to open the window, or fig.savefig to write a file. Notebooks and this course display the figure for you. #### Charts straight from pandas URL: https://www.msdevbuild.com/python/py-401/charts-from-pandas/ Every pandas Series and DataFrame has a .plot() method that draws with matplotlib for you. df.plot(x="month", y="revenue") draws a line, kind="bar" or .plot.barh() draws bars, and the index and column names become the axis labels. The common pattern is: groupby, sort, then plot. - series.plot(kind="bar") uses the index for the x-axis and the values for the bar heights. - df.plot(x="month", y=["north", "south"]) draws one line per column, with a legend. - .plot returns a matplotlib axes, so ax = s.plot.barh(); ax.set_title("...") adds a title. - Chain it: df.groupby("region")["revenue"].sum().sort_values().plot.barh(). Syntax: ```python s.plot(kind="bar") s.plot.barh() df.plot(x="col", y=["a", "b"]) ax = s.plot(); ax.set_title("...") ``` Example: ```python import pandas as pd sales = pd.DataFrame({ "region": ["North", "South", "North", "East", "South", "West", "East"], "revenue": [120, 90, 200, 60, 150, 40, 110], }) per_region = sales.groupby("region")["revenue"].sum().sort_values() print(per_region) ax = per_region.plot.barh(figsize=(6, 3), color="#2563eb") ax.set_title("North brings in the most revenue") ax.set_xlabel("Revenue") ``` Output: ```text region West 40 East 170 South 240 North 320 Name: revenue, dtype: int64 ``` Common mistake: Sort bars by value before plotting, .sort_values(), so the biggest and smallest are easy to find. Alphabetical order rarely tells a story. In the real world: A support team runs tickets.groupby("product")["minutes"].mean().sort_values().plot.barh() every Friday to see which product takes longest to support. **Q: How do I plot a pandas groupby result?** A: Aggregate first so you have one value per group, then call .plot on it, for example df.groupby("region")["revenue"].sum().plot(kind="bar"). **Q: How do I plot several columns as lines in pandas?** A: Use df.plot(x="date", y=["north", "south"]). Each column becomes a line and pandas adds a legend with the column names. #### Choosing the right chart URL: https://www.msdevbuild.com/python/py-401/choosing-the-right-chart/ Pick the chart from the question: a line chart for change over time, a bar chart to compare groups, a histogram to see how values are spread, and a scatter plot to see if two numbers move together. Avoid pie charts with more than a few slices, because people compare lengths far better than angles. A good chart answers one question at a glance. - Line: one value over time, such as daily sales. Bar: compare categories, such as revenue per region. - Histogram (ax.hist(values, bins=10)): how values are spread, such as delivery times. It shows the typical value and the outliers. - Scatter (ax.scatter(x, y)): whether two numbers are related, such as ad spend and sales. df["a"].corr(df["b"]) puts a number on it, from -1 to 1. - Several charts in one figure: fig, (ax1, ax2) = plt.subplots(1, 2) gives two axes side by side. Syntax: ```python ax.hist(values, bins=10) ax.scatter(x, y) fig, (ax1, ax2) = plt.subplots(1, 2) df["a"].corr(df["b"]) ``` Example: ```python import matplotlib.pyplot as plt import pandas as pd shops = pd.DataFrame({ "ad_spend": [5, 8, 12, 3, 15, 10, 7, 20], "sales": [52, 61, 80, 40, 95, 70, 58, 118], "delivery_days": [2, 3, 2, 5, 1, 2, 3, 2], }) fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(8, 3)) ax1.hist(shops["delivery_days"], bins=5) ax1.set_title("Most deliveries take 2 days") ax2.scatter(shops["ad_spend"], shops["sales"]) ax2.set_title("More ad spend, more sales") print("Correlation:", round(shops["ad_spend"].corr(shops["sales"]), 2)) ``` Output: ```text Correlation: 1.0 ``` Common mistake: Bar charts must start at zero. Cutting the axis at 90 makes a 2% difference look like a doubling. In the real world: A food delivery app plots a histogram of delivery times per city. Two cities with the same average look different: one has a long tail of 90-minute orders that the average hid. **Q: When should I use a histogram instead of a bar chart?** A: Use a histogram for one numeric column to see how its values are spread across ranges. Use a bar chart to compare a value between named categories such as regions or products. **Q: Does a high correlation mean one thing causes the other?** A: No. Correlation only says two numbers move together. A third factor may drive both, so test causes with experiments or domain knowledge. ### Module 6: Analysis end to end #### Exploratory analysis checklist URL: https://www.msdevbuild.com/python/py-401/exploratory-analysis-checklist/ Exploratory data analysis (EDA) is the first look at a new dataset to learn what it holds and what is wrong with it before you trust any answer. A repeatable checklist covers size (shape), types (dtypes), gaps (isna().sum()), repeats (duplicated().sum()), ranges (describe()) and categories (value_counts()). Only then do you start answering the business question. - Size and types: df.shape and df.dtypes. Numbers stored as text and dates stored as text show up here. - Gaps and repeats: df.isna().sum() and df.duplicated().sum(). Each one becomes a cleaning step from module 3. - Ranges: df.describe() gives count, mean, min, max and quartiles per number column. A min of -5 units or a max 100 times the median is a red flag. - Categories: df["region"].value_counts() shows each category and how often it appears, which reveals typos like "north" and "North". Syntax: ```python df.shape; df.dtypes df.isna().sum(); df.duplicated().sum() df.describe() df["col"].value_counts() ``` Example: ```python import io import pandas as pd csv_text = """order_id,region,units,price 1,North,3,2.5 2,north,2,2.5 3,South,,3.0 4,East,5,250 4,East,5,250 5,South,4,3.0 """ df = pd.read_csv(io.StringIO(csv_text)) print(df.shape) print(df.isna().sum().to_dict()) print("duplicates:", df.duplicated().sum()) print(df["region"].value_counts().to_dict()) print(df["price"].describe()[["min", "50%", "max"]].to_dict()) ``` Output: ```text (6, 4) {'order_id': 0, 'region': 0, 'units': 1, 'price': 0} duplicates: 1 {'South': 2, 'East': 2, 'North': 1, 'north': 1} {'min': 2.5, '50%': 3.0, 'max': 250.0} ``` Common mistake: Write your checks as a function, def first_look(df):, and run it on every new file. A checklist you do not have to remember is a checklist you actually run. In the real world: A bank's data team runs the same EDA notebook on every new data feed before it reaches the risk models. It once caught a feed where every amount was suddenly 100 times larger: a change from pounds to pence. **Q: What are the first steps of exploratory data analysis in Python?** A: Load the data, then check shape, dtypes, missing values with isna().sum(), duplicates with duplicated().sum(), number ranges with describe() and categories with value_counts(). Fix what you find before analysing. **Q: What is the difference between df.info() and df.describe()?** A: info lists every column with its type and count of non-missing values. describe gives statistics such as mean, min, max and quartiles for the number columns. #### Lab: Sales analysis URL: https://www.msdevbuild.com/python/py-401/sales-analysis-lab/ A sales analysis loads the raw export, adds the numbers you need (revenue = units × price), and answers each business question with one groupby: revenue by month, by region and by product. idxmax() names the winner of each, and a line chart shows the trend for the slide. This lab combines every module of PY-401 in about 20 lines. - Load and fix types: read_csv(..., parse_dates=["date"]), so dates group by month. - Add measures: df["revenue"] = df["units"] * df["unit_price"] is vectorised maths from module 1. - Answer with groupby: df.groupby(df["date"].dt.to_period("M"))["revenue"].sum() gives revenue per month. idxmax() returns the label of the biggest value. - Present: plot the monthly series as a line with a title that states the finding. Save your notebook and the chart to a GitHub repo as a portfolio piece. Syntax: ```python df["revenue"] = df["units"] * df["unit_price"] monthly = df.groupby(df["date"].dt.to_period("M"))["revenue"].sum() monthly.idxmax() ``` Example: ```python import io import pandas as pd csv_text = """date,region,product,units,unit_price 2026-01-05,North,Tea,30,2.5 2026-01-12,South,Coffee,22,3.0 2026-01-19,East,Cake,8,4.5 2026-01-26,North,Coffee,25,3.0 2026-02-02,South,Tea,40,2.5 2026-02-09,East,Coffee,18,3.0 2026-02-16,North,Cake,12,4.5 2026-02-23,West,Tea,15,2.5 2026-03-02,North,Tea,35,2.5 2026-03-09,South,Cake,20,4.5 2026-03-16,East,Tea,28,2.5 2026-03-23,West,Coffee,30,3.0 2026-03-30,North,Coffee,33,3.0 """ df = pd.read_csv(io.StringIO(csv_text), parse_dates=["date"]) df["revenue"] = df["units"] * df["unit_price"] monthly = df.groupby(df["date"].dt.to_period("M"))["revenue"].sum() by_region = df.groupby("region")["revenue"].sum().sort_values(ascending=False) by_product = df.groupby("product")["revenue"].sum().sort_values(ascending=False) print(monthly) print("Best month:", monthly.idxmax()) print("Best region:", by_region.idxmax(), by_region.max()) print("Best product:", by_product.idxmax(), by_product.max()) ax = monthly.plot(marker="o", figsize=(6, 3), title="March was the best month by far") ax.set_ylabel("Revenue") ``` Output: ```text date 2026-01 252.0 2026-02 245.5 2026-03 436.5 Freq: M, Name: revenue, dtype: float64 Best month: 2026-03 Best region: North 390.5 Best product: Coffee 384.0 ``` Common mistake: Answer the question that was asked, then add one surprise you found. "Tea sold most units, but Coffee made the most money" is the kind of line people remember. In the real world: This is the weekly job of a retail analyst: the same groupbys on a fresh export every Monday, often turned into a scheduled script (PY-310 Automation) or a dashboard (PY-410). **Q: How do I group sales by month in pandas?** A: Make sure the date column is a datetime (parse_dates or pd.to_datetime), then group by df["date"].dt.to_period("M"), or use df.resample("MS", on="date") for a time-series result. **Q: Is a sales analysis a good data analyst portfolio project?** A: Yes, if it starts from a raw file, shows the cleaning steps, answers clear business questions and ends with one or two charts and a written conclusion. Put it in a GitHub repository with a short README. ## System Design URL: https://www.msdevbuild.com/system-design/ ### Fundamentals The vocabulary every design discussion uses, and how to estimate before you draw. - Scalability: vertical vs horizontal (Beginner) - Latency vs throughput (Beginner) - Availability and SLAs (Beginner) - CAP and PACELC (Intermediate) - Consistency models (Intermediate) - Back-of-the-envelope estimation (Intermediate) ### Building blocks The components that appear in almost every architecture diagram, and when to reach for each. - DNS and load balancers (Beginner) - CDN and edge caching (Beginner) - Caching strategies (Intermediate) - API gateway and rate limiting (Intermediate) - SQL vs NoSQL (Beginner) - Replication and sharding (Advanced) - Consistent hashing (Advanced) - Message queues and streams (Intermediate) - Object storage and search (Intermediate) ### Architecture patterns Proven shapes for services and data, with the trade-offs nobody puts on the slide. - Monolith vs microservices (Beginner) - Event-driven architecture (Intermediate) - CQRS and event sourcing (Advanced) - Saga and distributed transactions (Advanced) - Circuit breaker, retries and idempotency (Intermediate) - Strangler fig migration (Intermediate) ### Reliability and operations Keeping a system up, knowing when it is not, and recovering when it falls over. - Observability: logs, metrics, traces (Beginner) - SLOs and error budgets (Intermediate) - Disaster recovery and backups (Intermediate) - Multi-region design (Advanced) - Deployment strategies (Intermediate) ### Security design Identity, secrets and isolation designed in from the first diagram. - Authentication vs authorization (Beginner) - OAuth 2.0 and OpenID Connect (Intermediate) - Secrets management (Intermediate) - Zero trust (Advanced) - Multi-tenant isolation (Advanced) ### Case studies Classic interview and real-world systems, designed end to end. - URL shortener (Beginner) - Rate limiter (Intermediate) - Chat system (Intermediate) - News feed (Intermediate) - Notification service (Intermediate) - Search autocomplete (Intermediate) - Payment system (Advanced) - Video streaming (Advanced) - Ride-hailing (Advanced) ### AI system design Designing with LLMs in the loop: retrieval, agents, cost, latency and guardrails. - RAG pipelines (Intermediate) - LLM gateway (Intermediate) - Agent architectures (Advanced) - Evaluation and guardrails (Advanced) - Cost and latency control (Intermediate) ### Mobile and client design Apps that work offline, sync safely and talk to APIs built for phones. - Offline-first sync (Intermediate) - Push notifications at scale (Intermediate) - .NET MAUI and Flutter app architecture (Intermediate) - API design for mobile clients (Beginner) ### Azure mapping Every pattern above, mapped to the Azure services that implement it. - Azure building blocks cheat sheet (Beginner) - Azure reference architectures (Intermediate) - Well-Architected Framework in practice (Advanced) ## Frequently asked questions ### What is MSDEVBUILD? MSDEVBUILD (Multi-Stack Dev Build) is a free learning platform by Suthahar Jegatheesan for cloud, AI, mobile and system design. It has three parts: this home site with System Design and your profile, Azure for certification practice, and the blog for real engineering stories. ### Can I learn Python on MSDEVBUILD? Yes. MSDEVBUILD teaches Python free from zero to job-ready: every lesson runs real Python in your browser and animates what the code does, then you solve a challenge and take a quiz. Roadmaps cover AI, development, data, automation and cloud, and there is a path for children aged 8 to 14. ### Is MSDEVBUILD free? Yes. Every lesson, System Design topic, practice question and article is free, and an account is optional. Signing in only adds things like synced progress and a public profile. ### Do I need an account, and does one account work everywhere? No account is needed to learn. If you sign in with Google, the same account works on msdevbuild.com, the blog and Azure: sign in on one and you are signed in on all of them. ### How do I get my own public profile? Sign in, open My profile, pick a username and choose what to show, then press Publish. Your page goes live at msdevbuild.com/u/your-username. Nothing is public until you publish, and you can take it down at any time. ### How do I edit my profile? Open My profile while signed in. Change your name, headline, bio, country and links, then press Save. The same profile is used on every MSDEVBUILD site. ### Who can see my profile? Only you can see your private profile. Your public profile shows only the fields you choose, and only after you publish it. MSDEVBUILD never posts anything for you. ### What does the System Design section cover? System Design covers nine topic groups: fundamentals, building blocks, architecture patterns, reliability, security, case studies, AI system design, mobile design and Azure mapping. Each topic follows the same path: requirements, estimates, a diagram, trade-offs and how to build it on Azure. ### Which courses does MSDEVBUILD offer? Free certification courses for Microsoft Azure, AI and GitHub exams such as AZ-900, AZ-104, AI-103 and GH-300, with more on the roadmap, plus Azure simulations, guided projects, multi-part blog series and System Design. Browse them all on the Courses page. ### Can I practise Azure without an Azure account? Yes. The Azure Simulator, the simulated Azure portal and the practice Cloud Shell all run in your browser, so you can break things on purpose with no subscription and no bill. ### Can I practise Azure certification exams here? Yes. Azure at azure.msdevbuild.com has lessons and practice exams for Azure certifications, starting with AZ-900, and your progress syncs when you are signed in. ### Where are the articles? All articles are on blog.msdevbuild.com: .NET, MAUI, Flutter, Azure, AI and career guides, written from real projects. Ask me a topic and I will find matching articles. ### Who is behind MSDEVBUILD? Suthahar Jegatheesan, a Cloud, AI and Mobile Solutions Architect based in Malaysia, builds and writes MSDEVBUILD. ### How do I contact MSDEVBUILD? Use the contact form on the blog, or reach Suthahar on LinkedIn. For account deletion, say so in the message. ## Policies - Privacy Policy: https://www.msdevbuild.com/privacy/ - Data Protection: https://www.msdevbuild.com/data-protection/ - Site map: https://www.msdevbuild.com/sitemap/