├── Core Python Foundations ├── 01 Data Structures │ ├── 01 Lists │ │ ├── Python Lists.py │ │ └── list_projects.py │ ├── 02 Dictionaries │ │ ├── Dictionaries.py │ │ ├── dict_projects.py │ │ └── test.ipynb │ ├── 03 Tuples │ │ ├── Tuples.py │ │ └── tuple_projects.py │ ├── 04 Sets │ │ ├── Sets.py │ │ └── set_projects.py │ ├── 05 Strings │ │ ├── Strings.py │ │ └── string_projects.py │ └── 06 Frozen Sets │ │ ├── Frozen Sets.py │ │ └── frozenset_projects.py ├── 02 Control Flow │ ├── 01 If-Else Statements │ │ ├── If-Else Statements.py │ │ └── ifelse_projects.py │ ├── 02 Elif Statements │ │ ├── Elif Statements.py │ │ └── elif_projects.py │ ├── 03 Nested Conditionals │ │ ├── Nested Conditionals.py │ │ └── nestedconditionals_projects.py │ ├── 04 For Loops │ │ ├── For Loops.py │ │ └── forloops_projects.py │ ├── 05 While Loops │ │ ├── While Loops.py │ │ └── whileloops_projects.py │ ├── 06 Break Statement │ │ ├── Break Statement.py │ │ └── break_projects.py │ ├── 07 Continue Statement │ │ ├── Continue Statement.py │ │ └── continue_projects.py │ └── 08 Pass Statement │ │ ├── Pass Statement.py │ │ └── pass_projects.py ├── 03 Functions │ ├── Functions Overview.py │ └── functions_projects.py ├── 04 Comprehensions │ ├── 01 List Comprehensions │ │ ├── List Comprehensions.py │ │ └── list_comprehensions_projects.py │ ├── 02 Dictionary Comprehensions │ │ ├── Dictionary Comprehensions.py │ │ └── dictionary_comprehensions_projects.py │ ├── 03 Set Comprehensions │ │ ├── Set Comprehensions.py │ │ └── set_comprehensions_projects.py │ └── 04 Generator Expressions │ │ ├── Generator Expressions.py │ │ └── generator_expressions_projects.py ├── 05 Exception Handling │ ├── 01 Try-Except │ │ ├── Try-Except.py │ │ └── try_except_projects.py │ ├── 02 Multiple Except Blocks │ │ ├── Multiple Except Blocks.py │ │ └── multiple_except_projects.py │ ├── 03 Else Clause │ │ ├── Else Clause.py │ │ └── else_clause_projects.py │ ├── 04 Finally Clause │ │ ├── Finally Clause.py │ │ └── finally_clause_projects.py │ ├── 05 Raise Statement │ │ ├── Raise Statement.py │ │ └── raise_statement_projects.py │ └── 06 Custom Exceptions │ │ ├── Custom Exceptions.py │ │ └── custom_exceptions_projects.py ├── 06 Object-Oriented Programming │ ├── 01 Classes and Objects │ │ ├── Classes and Objects.py │ │ └── classes_objects_projects.py │ ├── 02 Attributes │ │ ├── Attributes.py │ │ └── attributes_projects.py │ ├── 03 Methods │ │ ├── Methods.py │ │ └── methods_projects.py │ ├── 04 Inheritance │ │ ├── Inheritance.py │ │ └── inheritance_projects.py │ ├── 05 Multiple Inheritance │ │ ├── Multiple Inheritance.py │ │ └── multiple_inheritance_projects.py │ ├── 06 Encapsulation │ │ ├── Encapsulation.py │ │ └── encapsulation_projects.py │ ├── 07 Polymorphism │ │ ├── Polymorphism.py │ │ └── polymorphism_projects.py │ ├── 08 Abstract Classes │ │ ├── Abstract Classes.py │ │ └── abstract_classes_projects.py │ ├── 09 Static Methods │ │ ├── Static Methods.py │ │ └── static_methods_projects.py │ └── 10 Class Methods │ │ ├── Class Methods.py │ │ └── class_methods_projects.py ├── 07 Modules and Packages │ ├── 01 Importing Modules │ │ ├── Importing Modules.py │ │ └── importing_modules_projects.py │ ├── 02 Creating Modules │ │ ├── Creating Modules.py │ │ ├── creating_modules_projects.py │ │ └── retail_utils.py │ ├── 03 Packages │ │ ├── Packages.py │ │ ├── packages_projects.py │ │ └── retail_package │ │ │ ├── __init__.py │ │ │ ├── orders.py │ │ │ └── products.py │ └── 04 Standard Library │ │ ├── Standard Library - datetime.py │ │ ├── Standard Library - datetime_projects.py │ │ ├── Standard Library - math.py │ │ ├── Standard Library - math_projects.py │ │ ├── Standard Library - os.py │ │ ├── Standard Library - os_projects.py │ │ ├── Standard Library - random.py │ │ ├── Standard Library - random_projects.py │ │ ├── Standard Library - sys.py │ │ ├── Standard Library - sys_projects.py │ │ ├── Standard Library - time.py │ │ └── Standard Library - time_projects.py ├── 08 File Handling │ ├── 01 Reading Files │ │ ├── Reading Files.py │ │ └── reading_files_projects.py │ ├── 02 Writing Files │ │ ├── Writing Files.py │ │ └── writing_files_projects.py │ └── 03 CSV Files │ │ ├── CSV Files.py │ │ └── csv_files_projects.py ├── 09 Iterators and Generators │ ├── 01 Iterators │ │ ├── Iterators.py │ │ └── iterators_projects.py │ ├── 02 Generators │ │ ├── Generators.py │ │ └── generators_projects.py │ └── 03 Yield Statement │ │ ├── Yield Statement.py │ │ └── yield_statement_projects.py └── 10 Decorators │ ├── 01 Function Decorators │ ├── Function Decorators.py │ └── function_decorators_projects.py │ └── 02 Class Decorators │ ├── Class Decorators.py │ └── class_decorators_projects.py ├── LICENSE ├── Python Coding Pattern Interview Questions with Ans └── README.md ├── Python Coding Practice Questions ├── Advanced │ └── README.md ├── Basic │ └── README.md ├── Intermediate │ └── README.md └── README.md ├── Python Interview Questions with Ans └── README.md └── README.md /Core Python Foundations/01 Data Structures/01 Lists/Python Lists.py: -------------------------------------------------------------------------------- 1 | # Python Data Structures: Lists 2 | # Purpose: Learn Lists, which are ordered, mutable collections that allow duplicate elements. 3 | # Key Features: Indexing, slicing, appending, removing, sorting, and more. 4 | 5 | # %% 1. Creating and Accessing Lists 6 | # Explanation: Lists are defined with square brackets []. Elements can be of any type (strings, numbers, etc.). 7 | # Lists are ordered, and you can access items using zero-based indexing or slicing. 8 | products = ["Laptop", "Smartphone", "Coffee Maker", 999.99, 50] 9 | print("1.1 Original List:", products) 10 | print("1.2 First item (index 0):", products[0]) # Access first item 11 | print("1.3 Last item (index -1):", products[-1]) # Negative indexing 12 | print("1.4 Slice (items 1 to 2):", products[0:2]) # Slicing (excludes index 3) 13 | print("1.5 Length of list:", len(products)) # Get list length 14 | 15 | # Mini-Exercise: Create a list of 3 fruits and print the second fruit. 16 | fruits = ["Apple", "Banana", "Orange"] 17 | print("1.6 Mini-Exercise: Second fruit:", fruits[1]) 18 | 19 | # %% 2. Modifying Lists 20 | # Explanation: Lists are mutable, meaning you can change their contents using methods like append(), remove(), or direct index assignment. 21 | products.append("Blender") # Add item to the end 22 | print("2.1 After append:", products) 23 | products[3] = 899.99 # Update price at index 3 24 | print("2.2 After update:", products) 25 | products.remove("Smartphone") # Remove specific item 26 | print("2.3 After remove:", products) 27 | popped_item = products.pop() # Remove and return last item 28 | print("2.4 Popped item:", popped_item, "New list:", products) 29 | 30 | # Mini-Exercise: Add a new item to fruits, update the first item, and pop the last item. 31 | fruits.append("Mango") 32 | fruits[0] = "Grape" 33 | popped_fruit = fruits.pop() 34 | print("2.5 Mini-Exercise: Updated fruits:", fruits, "Popped fruit:", popped_fruit) 35 | 36 | # %% 3. List Operations 37 | # Explanation: Lists support operations like concatenation (+), repetition (*), and in-place methods like sort() and reverse(). 38 | electronics = ["Mouse", "Keyboard"] 39 | combined = products + electronics # Combine two lists 40 | print("3.1 Concatenated list:", combined) 41 | repeated = electronics * 2 # Repeat list 42 | print("3.2 Repeated list:", repeated) 43 | numbers = [5, 2, 8, 1] 44 | numbers.sort() # Sort in ascending order 45 | print("3.3 Sorted numbers:", numbers) 46 | numbers.reverse() # Reverse the list 47 | print("3.4 Reversed numbers:", numbers) 48 | 49 | # Mini-Exercise: Create a list of 4 numbers, sort it, and concatenate it with fruits. 50 | numbers = [10, 3, 7, 1] 51 | numbers.sort() 52 | combined_with_fruits = numbers + fruits 53 | print("3.5 Mini-Exercise: Sorted numbers + fruits:", combined_with_fruits) 54 | 55 | # %% 4. Common List Methods 56 | # Explanation: Lists have built-in methods for tasks like finding items, counting occurrences, or extending lists. 57 | print("4.1 Index of 'Laptop':", products.index("Laptop")) # Find index of item 58 | print("4.2 Count of 'Coffee Maker':", products.count("Coffee Maker")) # Count occurrences 59 | products.extend(["Headphones", "Monitor"]) # Add multiple items 60 | print("4.3 After extend:", products) 61 | products.clear() # Remove all items 62 | print("4.4 After clear:", products) 63 | 64 | # Mini-Exercise: Create a list, use extend() to add two items, and find the index of one item. 65 | items = ["Pen", "Notebook"] 66 | items.extend(["Pencil", "Eraser"]) 67 | print("4.5 Mini-Exercise: Extended list:", items, "Index of 'Pencil':", items.index("Pencil")) 68 | 69 | # %% 5. Exercises for Practice 70 | # Exercise 1: Create a list of 5 product prices, add a new price, update the second price, and sort the list. 71 | prices = [499.99, 299.99, 49.99, 89.99, 199.99] 72 | prices.append(399.99) 73 | prices[1] = 349.99 74 | prices.sort() 75 | print("5.1 Exercise 1 - Sorted prices:", prices) 76 | 77 | # Exercise 2: Create a list of categories, remove one category, and print the length of the final list. 78 | categories = ["Electronics", "Appliances", "Furniture", "Clothing"] 79 | categories.remove("Furniture") 80 | print("5.2 Exercise 2 - Categories length:", len(categories)) 81 | 82 | # Exercise 3: Combine two lists (products and quantities), pop the last item, and reverse the combined list. 83 | products = ["Laptop", "Coffee Maker"] # Reset products for exercise 84 | quantities = [10, 20, 30] 85 | combined_list = products + quantities 86 | combined_list.pop() 87 | combined_list.reverse() 88 | print("5.3 Exercise 3 - Reversed combined list:", combined_list) 89 | 90 | # %% 6. Notes for Further Learning 91 | # - Lists are versatile but can be slow for very large datasets (consider arrays or other structures later). 92 | # - Indexing starts at 0; negative indices (-1 is last item) are useful. 93 | # - Use list comprehension for advanced operations (covered later). 94 | # - Common use cases: Storing data for ML models, managing app inventories, etc. 95 | # Try the projects below to deepen your understanding! -------------------------------------------------------------------------------- /Core Python Foundations/01 Data Structures/02 Dictionaries/Dictionaries.py: -------------------------------------------------------------------------------- 1 | # Python Data Structures: Dictionaries 2 | # Purpose: Learn Dictionaries, unordered, mutable collections of key-value pairs. 3 | # Key Features: Fast lookups by key, unique keys, flexible values, order preserved (Python 3.7+). 4 | 5 | # %% 1. Creating and Accessing Dictionaries 6 | # Explanation: Dictionaries use curly braces {} with key-value pairs. Keys are unique and immutable (e.g., strings, numbers). 7 | # Values can be any type. Access values using keys or get() for safe access. 8 | product = { 9 | "id": 1, 10 | "name": "Laptop Pro", 11 | "price": 999.99, 12 | "category": "Electronics" 13 | } 14 | print("1.1 Dictionary:", product) 15 | print("1.2 Name:", product["name"]) # Access by key (raises KeyError if key missing) 16 | print("1.3 Price:", product.get("price")) # Safe access with get() 17 | print("1.4 Missing key:", product.get("stock", "Not found")) # Default value for missing key 18 | 19 | # Mini-Exercise: Create a dictionary for a book and print its title. 20 | book = {"title": "1984", "author": "George Orwell", "year": 1949} 21 | print("1.5 Mini-Exercise: Book title:", book["title"]) 22 | 23 | # %% 2. Modifying Dictionaries 24 | # Explanation: Dictionaries are mutable. Add/update key-value pairs with assignment or update(). 25 | # Remove items with pop() or popitem(). Use del for specific keys. 26 | product["stock"] = 50 # Add new key-value pair 27 | print("2.1 After adding stock:", product) 28 | product["price"] = 899.99 # Update existing key 29 | print("2.2 After updating price:", product) 30 | product.update({"category": "Premium Electronics", "warranty": "2 years"}) # Update multiple 31 | print("2.3 After update:", product) 32 | removed = product.pop("warranty") # Remove specific key, return value 33 | print("2.4 Removed:", removed, "Dictionary:", product) 34 | del product["stock"] # Remove key using del 35 | print("2.5 After del stock:", product) 36 | 37 | # Mini-Exercise: Add a rating to book, update year to 1950, and pop author. 38 | book["rating"] = 4.8 39 | book["year"] = 1950 40 | popped_author = book.pop("author") 41 | print("2.6 Mini-Exercise: Updated book:", book, "Popped author:", popped_author) 42 | 43 | # %% 3. Dictionary Operations 44 | # Explanation: Access keys, values, or items (key-value pairs). Check membership with 'in'. 45 | # Use len() for size. Dictionaries support iteration over keys, values, or items. 46 | print("3.1 Keys:", list(product.keys())) # Get all keys 47 | print("3.2 Values:", list(product.values())) # Get all values 48 | print("3.3 Items:", list(product.items())) # Get key-value pairs 49 | print("3.4 Is 'name' in keys?:", "name" in product) # Check key existence 50 | print("3.5 Dictionary size:", len(product)) # Number of key-value pairs 51 | 52 | # Mini-Exercise: Print all items in book and check if 'title' exists. 53 | print("3.6 Mini-Exercise: Book items:", list(book.items())) 54 | print("3.7 Is 'title' in book?:", "title" in book) 55 | 56 | # %% 4. Dictionary Methods 57 | # Explanation: Methods like copy(), clear(), setdefault(), and fromkeys() enhance functionality. 58 | # copy() creates a shallow copy, setdefault() adds a key with a default if absent. 59 | product_copy = product.copy() # Create a shallow copy 60 | print("4.1 Copy:", product_copy) 61 | product.setdefault("discount", 0.0) # Add key if not exists 62 | print("4.2 After setdefault discount:", product) 63 | default_dict = dict.fromkeys(["id", "name"], "Unknown") # Create dict with default values 64 | print("4.3 Fromkeys example:", default_dict) 65 | # product.clear() # Clears all items (commented to preserve data) 66 | # print("4.4 After clear:", product) 67 | 68 | # Mini-Exercise: Create a copy of book, add a default key 'pages' with value 0, and print copy. 69 | book_copy = book.copy() 70 | book_copy.setdefault("pages", 0) 71 | print("4.5 Mini-Exercise: Book copy with pages:", book_copy) 72 | 73 | # %% 5. Exercises for Practice 74 | # Exercise 1: Create a dictionary for a product, add a quantity key, update the price, and print all keys. 75 | item = {"id": 2, "name": "Smartphone", "price": 699.99} 76 | item["quantity"] = 100 77 | item["price"] = 649.99 78 | print("5.1 Exercise 1 - Keys:", list(item.keys())) 79 | 80 | # Exercise 2: Use update() to add category and rating to a dictionary, then remove rating. 81 | item = {"id": 3, "name": "Coffee Maker"} 82 | item.update({"category": "Appliances", "rating": 4.5}) 83 | item.pop("rating") 84 | print("5.2 Exercise 2 - Updated dictionary:", item) 85 | 86 | # Exercise 3: Check if a key exists in a dictionary and print its value using get(). 87 | check_key = "category" 88 | value = item.get(check_key, "Not found") 89 | print(f"5.3 Exercise 3 - Value for {check_key}:", value) 90 | 91 | # Exercise 4: Create a dictionary from a list of keys with a default value, then modify one value. 92 | keys = ["name", "price", "stock"] 93 | new_dict = dict.fromkeys(keys, "TBD") 94 | new_dict["price"] = 299.99 95 | print("5.4 Exercise 4 - Modified dictionary:", new_dict) 96 | 97 | # %% 6. Notes for Further Learning 98 | # - Dictionaries are ideal for fast key-based lookups (e.g., ML model configs, web app data). 99 | # - Keys must be immutable (strings, numbers, tuples). Values can be any type. 100 | # - Use dictionary comprehension for advanced operations (e.g., {k: v*2 for k, v in dict.items()}). 101 | # - Common use cases: Storing user profiles, caching results, mapping data. 102 | # - Try the projects below to apply these concepts! -------------------------------------------------------------------------------- /Core Python Foundations/01 Data Structures/02 Dictionaries/test.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "code", 5 | "execution_count": null, 6 | "id": "e6db0e50", 7 | "metadata": {}, 8 | "outputs": [], 9 | "source": [ 10 | "# Employee Database\n", 11 | "# Difficulty: Intermediate\n", 12 | "# Description: Store employee details in a dictionary with nested information.\n", 13 | "# Objective: Work with nested dictionaries and iteration.\n", 14 | "# Tasks:\n", 15 | "# Create a dictionary with 3 employees (id: {name, department}).\n", 16 | "# Add a new employee.\n", 17 | "# Print all employee names and their departments.\n", 18 | "# Count the number of employees.\n", 19 | "# Expected Output:\n", 20 | "# text\n", 21 | "\n", 22 | "# Copy\n", 23 | "# Employee 1: Alice, HR\n", 24 | "# Employee 2: Bob, IT\n", 25 | "# Employee 3: Charlie, Sales\n", 26 | "# Employee 4: Dana, Marketing\n", 27 | "# Total employees: 4\n", 28 | "# Concepts Covered: Nested dictionaries, items(), len().\n", 29 | "\n", 30 | "employees = {\n", 31 | " 1: {'name': 'Alice', 'department': 'HR'},\n", 32 | " 2: {'name': 'Bob', 'department': 'IT'},\n", 33 | " 3: {'name': 'Charlie', 'department': 'Sales'}\n", 34 | "}\n", 35 | "\n", 36 | "employees[4] = {'name': 'Dana', 'department': 'Marketing'}\n", 37 | "\n", 38 | "for emp_id, details " 39 | ] 40 | } 41 | ], 42 | "metadata": { 43 | "kernelspec": { 44 | "display_name": "base", 45 | "language": "python", 46 | "name": "python3" 47 | }, 48 | "language_info": { 49 | "name": "python", 50 | "version": "3.12.7" 51 | } 52 | }, 53 | "nbformat": 4, 54 | "nbformat_minor": 5 55 | } 56 | -------------------------------------------------------------------------------- /Core Python Foundations/01 Data Structures/03 Tuples/Tuples.py: -------------------------------------------------------------------------------- 1 | # Python Data Structures: Tuples 2 | # Purpose: Learn Tuples, ordered, immutable collections that allow duplicates. 3 | # Key Features: Lightweight, hashable, memory-efficient, ideal for fixed data. 4 | 5 | # %% 1. Creating and Accessing Tuples 6 | # Explanation: Tuples are defined with parentheses () or commas. Elements can be of any type. 7 | # Access items using zero-based indexing or slicing. Negative indices count from the end. 8 | order = (101, "Laptop Pro", 2, 1999.98) 9 | print("1.1 Tuple:", order) 10 | print("1.2 Order ID (index 0):", order[0]) # Access by index 11 | print("1.3 Last item (index -1):", order[-1]) # Negative indexing 12 | print("1.4 Slice (items 1 to 2):", order[1:3]) # Slicing 13 | print("1.5 Length of tuple:", len(order)) # Get tuple length 14 | 15 | # Mini-Exercise: Create a tuple of 3 coordinates and print the second coordinate. 16 | coords = (10, 20, 30) 17 | print("1.6 Mini-Exercise: Second coordinate:", coords[1]) 18 | 19 | # %% 2. Tuple Operations 20 | # Explanation: Tuples support concatenation (+), repetition (*), and membership tests (in). 21 | # Tuples are immutable, so operations create new tuples rather than modifying the original. 22 | items = ("Mouse", "Keyboard") 23 | combined = order + items # Concatenate tuples 24 | print("2.1 Combined tuple:", combined) 25 | repeated = items * 2 # Repeat tuple 26 | print("2.2 Repeated tuple:", repeated) 27 | print("2.3 Is 'Laptop Pro' in order?:", "Laptop Pro" in order) # Membership test 28 | print("2.4 Is 'Tablet' in order?:", "Tablet" in order) # Negative membership test 29 | 30 | # Mini-Exercise: Concatenate coords with (40, 50) and check if 20 is in the result. 31 | more_coords = (40, 50) 32 | combined_coords = coords + more_coords 33 | print("2.5 Mini-Exercise: Combined coords:", combined_coords, "Is 20 in tuple?:", 20 in combined_coords) 34 | 35 | # %% 3. Tuple Methods 36 | # Explanation: Tuples have only two methods: count() and index(), due to immutability. 37 | # count() returns occurrences of an item, index() returns the first index of an item. 38 | numbers = (1, 2, 2, 3, 1) 39 | print("3.1 Count of 2:", numbers.count(2)) # Count occurrences 40 | print("3.2 Index of 3:", numbers.index(3)) # Find first index 41 | print("3.3 Count of 5:", numbers.count(5)) # Count non-existent item 42 | 43 | # Mini-Exercise: Create a tuple with repeated items and print the count of one item. 44 | repeated_tuple = ("apple", "banana", "apple", "cherry") 45 | print("3.4 Mini-Exercise: Count of 'apple':", repeated_tuple.count("apple")) 46 | 47 | # %% 4. Tuple Unpacking 48 | # Explanation: Unpacking assigns tuple elements to variables. Use * for variable-length unpacking. 49 | # Number of variables must match tuple length or use * to capture extras. 50 | order_id, product_name, quantity, total = order # Standard unpacking 51 | print("4.1 Unpacked - ID:", order_id, "Product:", product_name, "Quantity:", quantity, "Total:", total) 52 | first, *middle, last = numbers # Variable-length unpacking 53 | print("4.2 Unpacked numbers - First:", first, "Middle:", middle, "Last:", last) 54 | 55 | # Mini-Exercise: Unpack coords into x, y, z and print y. 56 | x, y, z = coords 57 | print("4.3 Mini-Exercise: Y coordinate:", y) 58 | 59 | # %% 5. Exercises for Practice 60 | # Exercise 1: Create a tuple of 4 product details, access the third item, and print its length. 61 | product = (1, "Smartphone", 699.99, 100) 62 | third_item = product[2] 63 | print("5.1 Exercise 1 - Third item:", third_item, "Length:", len(product)) 64 | 65 | # Exercise 2: Concatenate two tuples (product info and stock) and check for an item’s presence. 66 | stock = (50, 20) 67 | combined = product + stock 68 | print("5.2 Exercise 2 - Combined:", combined, "Is 699.99 in tuple?:", 699.99 in combined) 69 | 70 | # Exercise 3: Unpack a tuple of order details and print the variables. 71 | order_details = (102, "Coffee Maker", 3, 149.97) 72 | o_id, o_product, o_qty, o_total = order_details 73 | print("5.3 Exercise 3 - Unpacked: ID:", o_id, "Product:", o_product, "Qty:", o_qty, "Total:", o_total) 74 | 75 | # Exercise 4: Create a tuple with duplicates, find the index of an item, and count another. 76 | data = (10, 20, 10, 30, 20) 77 | index_30 = data.index(30) 78 | count_10 = data.count(10) 79 | print("5.4 Exercise 4 - Index of 30:", index_30, "Count of 10:", count_10) 80 | 81 | # %% 6. Notes for Further Learning 82 | # - Tuples are immutable, ideal for fixed data (e.g., coordinates, database records, dictionary keys). 83 | # - Tuples are hashable, allowing use as dictionary keys or set elements. 84 | # - Use tuples over lists for memory efficiency when data won’t change. 85 | # - Common use cases: Returning multiple values from functions, storing ML dataset points. 86 | # - Try the projects below to apply these concepts! -------------------------------------------------------------------------------- /Core Python Foundations/01 Data Structures/06 Frozen Sets/Frozen Sets.py: -------------------------------------------------------------------------------- 1 | # Python Data Structures: Frozen Sets 2 | # Purpose: Learn Frozen Sets, immutable, unordered collections of unique elements. 3 | # Key Features: Hashable (usable as dictionary keys), supports set operations, deduplication. 4 | 5 | # %% 1. Creating and Accessing Frozen Sets 6 | # Explanation: Frozen sets are created with frozenset() from iterables (lists, sets, etc.). 7 | # Elements must be hashable (immutable). Access is limited to membership tests (in) since unordered. 8 | categories = frozenset(["Electronics", "Appliances", "Furniture"]) 9 | print("1.1 Frozen Set:", categories) 10 | print("1.2 Is 'Electronics' in frozen set?:", "Electronics" in categories) 11 | print("1.3 Is 'Books' in frozen set?:", "Books" in categories) 12 | print("1.4 Length of frozen set:", len(categories)) # Number of elements 13 | empty_fset = frozenset() # Empty frozen set 14 | print("1.5 Empty frozen set:", empty_fset) 15 | 16 | # Mini-Exercise: Create a frozen set of 3 numbers and check if one is present. 17 | numbers = frozenset([1, 2, 3]) 18 | print("1.6 Mini-Exercise: Is 2 in numbers?:", 2 in numbers) 19 | 20 | # %% 2. Frozen Set Operations 21 | # Explanation: Frozen sets support union (|), intersection (&), difference (-), and symmetric difference (^). 22 | # Operations return new frozen sets due to immutability. Identical to regular set operations. 23 | set1 = frozenset(["Laptop", "Smartphone", "Tablet"]) 24 | set2 = frozenset(["Smartphone", "Tablet", "Headphones"]) 25 | union = set1.union(set2) # All unique elements 26 | print("2.1 Union:", union) 27 | intersection = set1.intersection(set2) # Common elements 28 | print("2.2 Intersection:", intersection) 29 | difference = set1.difference(set2) # Elements in set1 but not set2 30 | print("2.3 Difference:", difference) 31 | sym_diff = set1.symmetric_difference(set2) # Elements in either but not both 32 | print("2.4 Symmetric Difference:", sym_diff) 33 | 34 | # Mini-Exercise: Find the intersection and union of two frozen sets of tags. 35 | tags1 = frozenset(["python", "coding"]) 36 | tags2 = frozenset(["coding", "tech"]) 37 | print("2.5 Mini-Exercise: Intersection:", tags1 & tags2, "Union:", tags1 | tags2) 38 | 39 | # %% 3. Frozen Set Methods 40 | # Explanation: Methods include copy(), issubset(), issuperset(), isdisjoint() (no add/remove due to immutability). 41 | # copy() returns a new frozen set (shallow). Methods mirror regular sets but preserve immutability. 42 | set_copy = categories.copy() # Shallow copy 43 | print("3.1 Copy:", set_copy) 44 | subset = frozenset(["Electronics", "Appliances"]) 45 | print("3.2 Is {'Electronics', 'Appliances'} a subset?:", subset.issubset(categories)) 46 | print("3.3 Is categories a superset of {'Furniture'}?:", categories.issuperset(frozenset(["Furniture"]))) 47 | print("3.4 Are categories and {'Books', 'Toys'} disjoint?:", categories.isdisjoint(frozenset(["Books", "Toys"]))) 48 | 49 | # Mini-Exercise: Check if numbers is a superset of {1}. 50 | print("3.5 Mini-Exercise: Is numbers a superset of {1}?:", numbers.issuperset(frozenset([1]))) 51 | 52 | # %% 4. Using Frozen Sets as Dictionary Keys 53 | # Explanation: Frozen sets are hashable, making them ideal as dictionary keys (unlike regular sets). 54 | # Use for mapping fixed collections to values (e.g., categories to descriptions). 55 | inventory = { 56 | frozenset(["Laptop", "Smartphone"]): "Electronics Stock", 57 | frozenset(["Coffee Maker", "Blender"]): "Appliances Stock" 58 | } 59 | print("4.1 Dictionary with frozen set keys:", inventory) 60 | print("4.2 Value for Electronics:", inventory[frozenset(["Laptop", "Smartphone"])]) 61 | # Accessing with equivalent frozen set 62 | key = frozenset(["Smartphone", "Laptop"]) # Same elements, different order 63 | print("4.3 Value with equivalent key:", inventory[key]) 64 | 65 | # Mini-Exercise: Create a dictionary with a frozen set key for tags and access its value. 66 | tag_dict = {frozenset(["python", "coding"]): "Programming Tags"} 67 | print("4.4 Mini-Exercise: Value for tags:", tag_dict[frozenset(["python", "coding"])]) 68 | 69 | # %% 5. Exercises for Practice 70 | # Exercise 1: Create a frozen set of product IDs and check for an ID’s presence. 71 | product_ids = frozenset([1, 2, 3, 4]) 72 | print("5.1 Exercise 1 - Is 3 in frozen set?:", 3 in product_ids) 73 | 74 | # Exercise 2: Find the union of two frozen sets of categories. 75 | cat1 = frozenset(["Electronics", "Appliances"]) 76 | cat2 = frozenset(["Appliances", "Furniture"]) 77 | union = cat1.union(cat2) 78 | print("5.2 Exercise 2 - Union:", union) 79 | 80 | # Exercise 3: Use a frozen set as a dictionary key to store a category description. 81 | desc = {frozenset(["Mouse", "Keyboard"]): "Peripherals"} 82 | print("5.3 Exercise 3 - Dictionary:", desc) 83 | 84 | # Exercise 4: Create two frozen sets and check if they are disjoint. 85 | set_a = frozenset([1, 2, 3]) 86 | set_b = frozenset([4, 5, 6]) 87 | disjoint = set_a.isdisjoint(set_b) 88 | print("5.4 Exercise 4 - Are sets disjoint?:", disjoint) 89 | 90 | # %% 6. Notes for Further Learning 91 | # - Frozen sets are immutable and hashable, ideal for dictionary keys or set elements (e.g., ML model metadata, fixed configurations). 92 | # - Use regular sets for mutable operations; frozen sets for fixed, hashable data. 93 | # - Set operations (union, intersection, etc.) are identical to regular sets but return frozen sets. 94 | # - Common use cases: Caching unique identifiers, storing immutable groups in dictionaries. 95 | # - Try the projects below to apply these concepts! -------------------------------------------------------------------------------- /Core Python Foundations/01 Data Structures/06 Frozen Sets/frozenset_projects.py: -------------------------------------------------------------------------------- 1 | # Python Frozen Set Projects 2 | # Purpose: Apply Python Frozen Set knowledge through 5 optimized projects (Basic to Advanced). 3 | # Structure: Each project is separated by %% and includes description, tasks, and best solution. 4 | # Note: Solutions are designed for clarity, efficiency, and beginner learning. 5 | 6 | # %% Project 1: Category Key Generator 7 | # Difficulty: Basic 8 | # Description: Create a frozen set of product categories for use as a dictionary key. 9 | # Objective: Practice creating frozen sets and using them as keys. 10 | # Tasks: 11 | # - Create a frozen set of 3 product categories. 12 | # - Use it as a key in a dictionary to store a description. 13 | # - Check if a category is in the frozen set. 14 | # - Print the dictionary and membership result. 15 | categories = frozenset(["Electronics", "Appliances", "Furniture"]) 16 | category_dict = {categories: "Main Categories"} 17 | is_present = "Electronics" in categories 18 | print("Dictionary:", category_dict) 19 | print("Is 'Electronics' present?:", is_present) 20 | 21 | # %% Project 2: Unique ID Store 22 | # Difficulty: Basic 23 | # Description: Store unique product IDs in a frozen set. 24 | # Objective: Practice frozen set creation and membership testing. 25 | # Tasks: 26 | # - Create a frozen set from a list with duplicate IDs. 27 | # - Check if two IDs are present (one in, one out). 28 | # - Print the frozen set and membership results. 29 | ids = [1, 2, 2, 3, 4, 4] 30 | unique_ids = frozenset(ids) 31 | is_2_present = 2 in unique_ids 32 | is_5_present = 5 in unique_ids 33 | print("IDs:", unique_ids) 34 | print("Is 2 present?:", is_2_present) 35 | print("Is 5 present?:", is_5_present) 36 | 37 | # %% Project 3: Tag Overlap Analyzer 38 | # Difficulty: Intermediate 39 | # Description: Analyze overlapping tags between two frozen sets. 40 | # Objective: Use set operations (intersection, union). 41 | # Tasks: 42 | # - Create two frozen sets of tags. 43 | # - Find their intersection and union. 44 | # - Check if one is a subset of the other. 45 | # - Print the results. 46 | tags1 = frozenset(["python", "coding", "tutorial"]) 47 | tags2 = frozenset(["coding", "tech"]) 48 | intersection = tags1.intersection(tags2) 49 | union = tags1.union(tags2) 50 | is_subset = tags1.issubset(tags2) 51 | print("Intersection:", intersection) 52 | print("Union:", union) 53 | print("Is tags1 a subset of tags2?:", is_subset) 54 | 55 | # %% Project 4: Inventory Mapping 56 | # Difficulty: Advanced 57 | # Description: Map frozen sets of items to inventory locations. 58 | # Objective: Use frozen sets as dictionary keys for complex mappings. 59 | # Tasks: 60 | # - Create a dictionary with two frozen set keys (item groups) and location values. 61 | # - Add a new mapping. 62 | # - Access a value using an equivalent frozen set key. 63 | # - Print the dictionary and accessed value. 64 | inventory = { 65 | frozenset(["Laptop", "Smartphone"]): "Store A", 66 | frozenset(["Coffee Maker", "Blender"]): "Store B" 67 | } 68 | inventory[frozenset(["Mouse", "Keyboard"])] = "Store C" 69 | equivalent_key = frozenset(["Smartphone", "Laptop"]) # Same elements, different order 70 | location = inventory[equivalent_key] 71 | print("Inventory:", inventory) 72 | print("Location:", location) 73 | 74 | # %% Project 5: Permission Validator 75 | # Difficulty: Advanced 76 | # Description: Validate permissions using frozen sets in a configuration. 77 | # Objective: Use frozen sets for immutable permission groups and set operations. 78 | # Tasks: 79 | # - Create two frozen sets of permissions (allowed, required). 80 | # - Check if required permissions are a subset of allowed. 81 | # - Find permissions in allowed but not required (difference). 82 | # - Print the results. 83 | allowed = frozenset(["read", "write", "delete"]) 84 | required = frozenset(["read", "write"]) 85 | all_permitted = required.issubset(allowed) 86 | extra_perms = allowed.difference(required) 87 | print("Allowed:", allowed) 88 | print("Required:", required) 89 | print("All required permitted?:", all_permitted) 90 | print("Extra permissions:", extra_perms) -------------------------------------------------------------------------------- /Core Python Foundations/02 Control Flow/01 If-Else Statements/If-Else Statements.py: -------------------------------------------------------------------------------- 1 | # Python Control Flow: If-Else Statements 2 | # Purpose: Learn If-Else statements to execute code blocks based on conditions. 3 | # Key Features: Conditional branching for binary decision-making, foundational for control flow. 4 | 5 | # %% 1. Basic If-Else 6 | # Explanation: If the condition evaluates to True, execute the if-block; otherwise, execute the else-block. 7 | # Use for simple decisions (e.g., thresholding values). 8 | price = 999.99 9 | if price > 500: 10 | print("1.1 Premium product") 11 | else: 12 | print("1.1 Standard product") 13 | # Example with boolean 14 | is_available = True 15 | if is_available: 16 | print("1.2 Product in stock") 17 | else: 18 | print("1.2 Out of stock") 19 | 20 | # Mini-Exercise: Check if a quantity is positive and print "Valid quantity" or "Invalid quantity". 21 | quantity = 10 22 | if quantity > 0: 23 | print("1.3 Mini-Exercise: Valid quantity") 24 | else: 25 | print("1.3 Mini-Exercise: Invalid quantity") 26 | 27 | # %% 2. Multiple Conditions 28 | # Explanation: Combine conditions using logical operators: and (both true), or (either true), not (inverts). 29 | # Useful for complex decision rules (e.g., filtering items). 30 | stock = 50 31 | if price > 500 and stock < 100: 32 | print("2.1 High-value, low-stock item") 33 | else: 34 | print("2.1 Regular item") 35 | # Example with or 36 | category = "Electronics" 37 | if price > 1000 or category == "Electronics": 38 | print("2.2 Special handling required") 39 | else: 40 | print("2.2 Standard handling") 41 | 42 | # Mini-Exercise: Check if quantity is between 5 and 20 (inclusive) and print "Moderate stock" or "Check stock". 43 | if 5 <= quantity <= 20: 44 | print("2.3 Mini-Exercise: Moderate stock") 45 | else: 46 | print("2.3 Mini-Exercise: Check stock") 47 | 48 | # %% 3. Using If-Else with Data 49 | # Explanation: Apply if-else to process structured data (e.g., dictionaries, lists) for real-world tasks. 50 | # Common in data processing or user input validation. 51 | product = {"name": "Laptop Pro", "price": 999.99, "category": "Electronics"} 52 | if product["price"] >= 700: 53 | product["status"] = "Premium" 54 | else: 55 | product["status"] = "Standard" 56 | print("3.1 Product with status:", product) 57 | # Example with list 58 | prices = [200, 1200, 600] 59 | if max(prices) > 1000: 60 | print("3.2 Contains high-end item") 61 | else: 62 | print("3.2 All standard items") 63 | 64 | # Mini-Exercise: Add a "Low Stock" flag to product if stock < 30, else "Sufficient". 65 | product["stock"] = 25 66 | if product["stock"] < 30: 67 | product["low_stock"] = True 68 | else: 69 | product["low_stock"] = False 70 | print("3.3 Mini-Exercise: Updated product:", product) 71 | 72 | # %% 4. Exercises for Practice 73 | # Exercise 1: Check if a product’s stock is below 20 and print "Restock needed" or "Stock sufficient". 74 | stock_quantity = 15 75 | if stock_quantity < 20: 76 | print("4.1 Exercise 1 - Restock needed") 77 | else: 78 | print("4.1 Exercise 1 - Stock sufficient") 79 | 80 | # Exercise 2: Assign a discount (10% if price > 1000, 5% otherwise) and print the discounted price. 81 | item_price = 1200 82 | if item_price > 1000: 83 | discount = 0.1 84 | else: 85 | discount = 0.05 86 | discounted_price = item_price * (1 - discount) 87 | print("4.2 Exercise 2 - Discounted price:", discounted_price) 88 | 89 | # Exercise 3: Check if a product is in the "Electronics" category and print "Tech item" or "Non-tech item". 90 | product_category = "Appliances" 91 | if product_category == "Electronics": 92 | print("4.3 Exercise 3 - Tech item") 93 | else: 94 | print("4.3 Exercise 3 - Non-tech item") 95 | 96 | # Exercise 4: Check if a product’s price is between 500 and 1000 and stock > 10, print "Good deal" or "Check offer". 97 | price_check = 800 98 | stock_check = 15 99 | if 500 <= price_check <= 1000 and stock_check > 10: 100 | print("4.4 Exercise 4 - Good deal") 101 | else: 102 | print("4.4 Exercise 4 - Check offer") 103 | 104 | # %% 5. Notes for Further Learning 105 | # - Conditions must evaluate to True/False (e.g., ==, >, <, and, or, not). 106 | # - If-Else is ideal for binary decisions in ML (e.g., feature thresholding) or web apps (e.g., user role checks). 107 | # - Avoid deep nesting for readability; use elif or nested conditionals when needed. 108 | # - Use clear variable names and comments to document decision logic. 109 | # - Try the projects below to apply these concepts! -------------------------------------------------------------------------------- /Core Python Foundations/02 Control Flow/01 If-Else Statements/ifelse_projects.py: -------------------------------------------------------------------------------- 1 | # If-Else Projects 2 | # Purpose: Apply If-Else statements through 5 projects (Basic to Advanced). 3 | # Structure: Each project is separated by %% and includes description, tasks, and best solution. 4 | # Note: Solutions are designed for clarity, efficiency, and beginner learning. 5 | 6 | # %% Project 1: Price Tier Classifier 7 | # Difficulty: Basic 8 | # Description: Classify a product based on its price tier. 9 | # Objective: Practice basic if-else with comparison operators. 10 | # Tasks: 11 | # - Create a variable for product price. 12 | # - If price > 1000, classify as "Luxury"; otherwise, "Budget". 13 | # - Print the classification. 14 | price = 1200 15 | if price > 1000: 16 | classification = "Luxury" 17 | else: 18 | classification = "Budget" 19 | print("Classification:", classification) 20 | 21 | # %% Project 2: Stock Alert System 22 | # Difficulty: Basic 23 | # Description: Generate an alert based on stock level. 24 | # Objective: Use if-else with a single condition. 25 | # Tasks: 26 | # - Create a variable for stock quantity. 27 | # - If stock < 10, print "Critical stock"; otherwise, "Stock OK". 28 | # - Print the alert. 29 | stock = 5 30 | if stock < 10: 31 | alert = "Critical stock" 32 | else: 33 | alert = "Stock OK" 34 | print("Alert:", alert) 35 | 36 | # %% Project 3: Order Validator 37 | # Difficulty: Intermediate 38 | # Description: Validate an order based on price and quantity. 39 | # Objective: Use if-else with logical operators (and). 40 | # Tasks: 41 | # - Create variables for order price and quantity. 42 | # - If price > 500 and quantity > 0, print "Valid order"; otherwise, "Invalid order". 43 | # - Print the validation result. 44 | order_price = 600 45 | order_quantity = 2 46 | if order_price > 500 and order_quantity > 0: 47 | validation = "Valid order" 48 | else: 49 | validation = "Invalid order" 50 | print("Validation:", validation) 51 | 52 | # %% Project 4: Category-Based Pricing 53 | # Difficulty: Intermediate 54 | # Description: Adjust pricing based on product category. 55 | # Objective: Use if-else with dictionary data and string comparison. 56 | # Tasks: 57 | # - Create a dictionary with product name, price, and category. 58 | # - If category is "Electronics", increase price by 10%; otherwise, keep original. 59 | # - Print the product with updated price. 60 | product = {"name": "Laptop", "price": 1000, "category": "Electronics"} 61 | if product["category"] == "Electronics": 62 | product["price"] *= 1.1 63 | print("Updated product:", product) 64 | 65 | # %% Project 5: Shipping Cost Calculator 66 | # Difficulty: Advanced 67 | # Description: Calculate shipping cost based on order details. 68 | # Objective: Use if-else with multiple conditions and data processing. 69 | # Tasks: 70 | # - Create a dictionary with order weight, total, and express shipping flag. 71 | # - If weight > 5 or total > 1000, set base cost to $20; otherwise, $10. 72 | # - If express is True, add $15 to cost. 73 | # - Print the shipping cost. 74 | order = {"weight": 6, "total": 800, "express": True} 75 | if order["weight"] > 5 or order["total"] > 1000: 76 | cost = 20 77 | else: 78 | cost = 10 79 | if order["express"]: 80 | cost += 15 81 | print("Shipping cost:", cost) -------------------------------------------------------------------------------- /Core Python Foundations/02 Control Flow/02 Elif Statements/Elif Statements.py: -------------------------------------------------------------------------------- 1 | # Python Control Flow: Elif Statements 2 | # Purpose: Learn Elif statements to check multiple conditions sequentially. 3 | # Key Features: Extends if-else for multi-way branching, improves readability. 4 | 5 | # %% 1. Basic If-Elif-Else 6 | # Explanation: Check conditions in order; execute the first True block, or else-block if none are True. 7 | # Ideal for categorizing data with multiple tiers. 8 | price = 699.99 9 | if price > 1000: 10 | print("1.1 Luxury product") 11 | elif price > 500: 12 | print("1.1 Mid-range product") 13 | else: 14 | print("1.1 Budget product") 15 | # Example with boolean 16 | stock_alert = 30 17 | if stock_alert < 10: 18 | print("1.2 Critical alert") 19 | elif stock_alert <= 50: 20 | print("1.2 Warning alert") 21 | else: 22 | print("1.2 No alert") 23 | 24 | # Mini-Exercise: Classify a score (0-100) as "Fail" (< 60), "Pass" (60-80), or "Excellent" (> 80). 25 | score = 75 26 | if score < 60: 27 | print("1.3 Mini-Exercise: Fail") 28 | elif score <= 80: 29 | print("1.3 Mini-Exercise: Pass") 30 | else: 31 | print("1.3 Mini-Exercise: Excellent") 32 | 33 | # %% 2. Multiple Elif Clauses 34 | # Explanation: Use multiple elif clauses for fine-grained conditions, stopping at the first True. 35 | # Useful for tiered pricing or inventory management. 36 | stock = 30 37 | if stock > 100: 38 | print("2.1 Overstocked") 39 | elif stock > 50: 40 | print("2.1 Well-stocked") 41 | elif stock > 20: 42 | print("2.1 Moderately stocked") 43 | else: 44 | print("2.1 Low stock") 45 | # Example with ranges 46 | price_level = 1200 47 | if price_level > 2000: 48 | print("2.2 Ultra-premium") 49 | elif price_level > 1000: 50 | print("2.2 Premium") 51 | elif price_level > 500: 52 | print("2.2 Mid-tier") 53 | else: 54 | print("2.2 Entry-level") 55 | 56 | # Mini-Exercise: Categorize age as "Child" (< 13), "Teen" (13-19), "Adult" (20-64), or "Senior" (65+). 57 | age = 25 58 | if age < 13: 59 | print("2.3 Mini-Exercise: Child") 60 | elif age <= 19: 61 | print("2.3 Mini-Exercise: Teen") 62 | elif age <= 64: 63 | print("2.3 Mini-Exercise: Adult") 64 | else: 65 | print("2.3 Mini-Exercise: Senior") 66 | 67 | # %% 3. Elif with Complex Conditions 68 | # Explanation: Combine elif with logical operators (and, or) for complex decision-making. 69 | # Common in data filtering or business rules. 70 | product = {"name": "Smartphone", "price": 699.99, "stock": 100} 71 | if product["price"] > 1000 and product["stock"] < 50: 72 | print("3.1 High-value, low-stock") 73 | elif product["price"] > 500 and product["stock"] >= 50: 74 | print("3.1 High-value, sufficient stock") 75 | elif product["price"] <= 500: 76 | print("3.1 Affordable product") 77 | # Example with or 78 | if product["price"] > 1000 or product["stock"] < 20: 79 | print("3.2 Special monitoring") 80 | else: 81 | print("3.2 Standard monitoring") 82 | 83 | # Mini-Exercise: Tag a product as "Priority" (Electronics and stock < 30) or "Normal" (otherwise). 84 | if product["stock"] < 30 and product["name"] == "Smartphone": 85 | print("3.3 Mini-Exercise: Priority") 86 | else: 87 | print("3.3 Mini-Exercise: Normal") 88 | 89 | # %% 4. Exercises for Practice 90 | # Exercise 1: Categorize a product price as "Cheap" (< 100), "Moderate" (100-500), or "Expensive" (> 500). 91 | price = 250 92 | if price < 100: 93 | print("4.1 Exercise 1 - Cheap") 94 | elif price <= 500: 95 | print("4.1 Exercise 1 - Moderate") 96 | else: 97 | print("4.1 Exercise 1 - Expensive") 98 | 99 | # Exercise 2: Assign a stock status: "Critical" (< 10), "Low" (10-30), "Normal" (31-100), or "High" (> 100). 100 | stock_level = 25 101 | if stock_level < 10: 102 | print("4.2 Exercise 2 - Critical") 103 | elif stock_level <= 30: 104 | print("4.2 Exercise 2 - Low") 105 | elif stock_level <= 100: 106 | print("4.2 Exercise 2 - Normal") 107 | else: 108 | print("4.2 Exercise 2 - High") 109 | 110 | # Exercise 3: Check a product’s category and price to assign a tag: "Premium Tech" (Electronics, > 700), 111 | # "Standard Tech" (Electronics, <= 700), or "Non-Tech". 112 | category = "Electronics" 113 | price = 800 114 | if category == "Electronics" and price > 700: 115 | print("4.3 Exercise 3 - Premium Tech") 116 | elif category == "Electronics": 117 | print("4.3 Exercise 3 - Standard Tech") 118 | else: 119 | print("4.3 Exercise 3 - Non-Tech") 120 | 121 | # Exercise 4: Categorize order size as "Small" (< 5 items), "Medium" (5-20), "Large" (21-50), or "Bulk" (> 50). 122 | order_size = 15 123 | if order_size < 5: 124 | print("4.4 Exercise 4 - Small") 125 | elif order_size <= 20: 126 | print("4.4 Exercise 4 - Medium") 127 | elif order_size <= 50: 128 | print("4.4 Exercise 4 - Large") 129 | else: 130 | print("4.4 Exercise 4 - Bulk") 131 | 132 | # %% 5. Notes for Further Learning 133 | # - Elif statements reduce nested if-else, improving code readability. 134 | # - Only the first True condition’s block executes; subsequent conditions are skipped. 135 | # - Use in ML for feature categorization (e.g., binning values) or web apps for tiered pricing. 136 | # - Combine with logical operators for complex rules, but keep conditions clear. 137 | # - Try the projects below to apply these concepts! -------------------------------------------------------------------------------- /Core Python Foundations/02 Control Flow/02 Elif Statements/elif_projects.py: -------------------------------------------------------------------------------- 1 | # Elif Projects 2 | # Purpose: Apply Elif statements through 5 projects (Basic to Advanced). 3 | # Structure: Each project is separated by %% and includes description, tasks, and best solution. 4 | # Note: Solutions are designed for clarity, efficiency, and beginner learning. 5 | 6 | # %% Project 1: Price Range Classifier 7 | # Difficulty: Basic 8 | # Description: Classify a product’s price into multiple ranges. 9 | # Objective: Practice basic if-elif-else with multiple conditions. 10 | # Tasks: 11 | # - Create a variable for product price. 12 | # - Classify as "Cheap" (< 100), "Moderate" (100-500), or "Expensive" (> 500). 13 | # - Print the classification. 14 | price = 250 15 | if price < 100: 16 | classification = "Cheap" 17 | elif price <= 500: 18 | classification = "Moderate" 19 | else: 20 | classification = "Expensive" 21 | print("Classification:", classification) 22 | 23 | # %% Project 2: Stock Status Tagger 24 | # Difficulty: Basic 25 | # Description: Tag stock levels with descriptive statuses. 26 | # Objective: Use multiple elif clauses for categorization. 27 | # Tasks: 28 | # - Create a variable for stock quantity. 29 | # - Tag as "Critical" (< 10), "Low" (10-30), or "Sufficient" (> 30). 30 | # - Print the status. 31 | stock = 25 32 | if stock < 10: 33 | status = "Critical" 34 | elif stock <= 30: 35 | status = "Low" 36 | else: 37 | status = "Sufficient" 38 | print("Status:", status) 39 | 40 | # %% Project 3: Category Price Adjuster 41 | # Difficulty: Intermediate 42 | # Description: Adjust price based on product category and price tier. 43 | # Objective: Use elif with complex conditions and dictionary data. 44 | # Tasks: 45 | # - Create a dictionary with product name, price, and category. 46 | # - If Electronics and price > 700, tag "Premium Tech"; elif Electronics, tag "Standard Tech"; else "Other". 47 | # - Print the product with tag. 48 | product = {"name": "Smartphone", "price": 800, "category": "Electronics"} 49 | if product["category"] == "Electronics" and product["price"] > 700: 50 | product["tag"] = "Premium Tech" 51 | elif product["category"] == "Electronics": 52 | product["tag"] = "Standard Tech" 53 | else: 54 | product["tag"] = "Other" 55 | print("Updated product:", product) 56 | 57 | # %% Project 4: Order Size Evaluator 58 | # Difficulty: Intermediate 59 | # Description: Evaluate order size for processing priority. 60 | # Objective: Use multiple elif clauses with ranges. 61 | # Tasks: 62 | # - Create a variable for order size (number of items). 63 | # - Classify as "Small" (< 5), "Medium" (5-20), "Large" (21-50), or "Bulk" (> 50). 64 | # - Print the classification. 65 | order_size = 15 66 | if order_size < 5: 67 | size = "Small" 68 | elif order_size <= 20: 69 | size = "Medium" 70 | elif order_size <= 50: 71 | size = "Large" 72 | else: 73 | size = "Bulk" 74 | print("Order size:", size) 75 | 76 | # %% Project 5: Discount Tier System 77 | # Difficulty: Advanced 78 | # Description: Apply discounts based on order total and customer status. 79 | # Objective: Use elif with logical operators and data processing. 80 | # Tasks: 81 | # - Create a dictionary with order total and VIP status (True/False). 82 | # - If total > 2000 and VIP, discount 15%; elif total > 2000, 10%; elif total > 500, 5%; else 0%. 83 | # - Print the discounted total. 84 | order = {"total": 2000, "vip": True} 85 | if order["total"] > 2000 and order["vip"]: 86 | discount = 0.15 87 | elif order["total"] > 2000: 88 | discount = 0.1 89 | elif order["total"] > 500: 90 | discount = 0.05 91 | else: 92 | discount = 0 93 | discounted_total = order["total"] * (1 - discount) 94 | print("Discounted total:", discounted_total) -------------------------------------------------------------------------------- /Core Python Foundations/02 Control Flow/03 Nested Conditionals/nestedconditionals_projects.py: -------------------------------------------------------------------------------- 1 | # Nested Conditionals Projects 2 | # Purpose: Apply Nested Conditionals through 5 projects (Basic to Advanced). 3 | # Structure: Each project is separated by %% and includes description, tasks, and best solution. 4 | # Note: Solutions are designed for clarity, efficiency, and beginner learning. 5 | 6 | # %% Project 1: Stock Price Checker 7 | # Difficulty: Basic 8 | # Description: Check product price and stock for restocking needs. 9 | # Objective: Practice basic nested if statements. 10 | # Tasks: 11 | # - Create variables for price and stock. 12 | # - If price > 500, check if stock < 30; print "Restock expensive item" or "Sufficient stock". 13 | # - Else print "Budget item". 14 | # - Print the result. 15 | price = 600 16 | stock = 25 17 | if price > 500: 18 | if stock < 30: 19 | result = "Restock expensive item" 20 | else: 21 | result = "Sufficient stock" 22 | else: 23 | result = "Budget item" 24 | print(result) 25 | 26 | # %% Project 2: Category Stock Validator 27 | # Difficulty: Basic 28 | # Description: Validate stock for specific categories. 29 | # Objective: Use nested if with string comparison. 30 | # Tasks: 31 | # - Create variables for category and stock. 32 | # - If category is "Electronics", check if stock > 0; print "In stock" or "Out of stock". 33 | # - Else print "Non-Electronics". 34 | # - Print the result. 35 | category = "Electronics" 36 | stock = 10 37 | if category == "Electronics": 38 | if stock > 0: 39 | result = "In stock" 40 | else: 41 | result = "Out of stock" 42 | else: 43 | result = "Non-Electronics" 44 | print(result) 45 | 46 | # %% Project 3: Tech Product Pricer 47 | # Difficulty: Intermediate 48 | # Description: Price products based on category and stock. 49 | # Objective: Use nested if-elif with dictionary data. 50 | # Tasks: 51 | # - Create a dictionary with category, price, and stock. 52 | # - If category in ["Electronics", "Appliances"], check price > 500; if stock < 50, tag "Priority"; else "Standard". 53 | # - Else tag "Non-Tech". 54 | # - Print the product with tag. 55 | product = {"category": "Electronics", "price": 600, "stock": 20} 56 | if product["category"] in ["Electronics", "Appliances"]: 57 | if product["price"] > 500: 58 | if product["stock"] < 50: 59 | product["tag"] = "Priority" 60 | else: 61 | product["tag"] = "Standard" 62 | else: 63 | product["tag"] = "Standard" 64 | else: 65 | product["tag"] = "Non-Tech" 66 | print("Updated product:", product) 67 | 68 | # %% Project 4: Order Approval System 69 | # Difficulty: Intermediate 70 | # Description: Approve orders based on multiple criteria. 71 | # Objective: Use deep nesting with logical conditions. 72 | # Tasks: 73 | # - Create a dictionary with order total, items, and express flag. 74 | # - If total > 1000, check items > 0; if express, approve "Express Order"; else "Standard Order". 75 | # - Else print "Invalid Order". 76 | # - Print the result. 77 | order = {"total": 1500, "items": 3, "express": True} 78 | if order["total"] > 1000: 79 | if order["items"] > 0: 80 | if order["express"]: 81 | result = "Express Order" 82 | else: 83 | result = "Standard Order" 84 | else: 85 | result = "Invalid Order" 86 | else: 87 | result = "Invalid Order" 88 | print(result) 89 | 90 | # %% Project 5: Inventory Audit System 91 | # Difficulty: Advanced 92 | # Description: Audit inventory based on multiple conditions. 93 | # Objective: Use deep nesting with complex data processing. 94 | # Tasks: 95 | # - Create a dictionary with category, price, stock, and is_tech flag. 96 | # - If is_tech, check price > 700; if stock < 30, flag "Critical"; else "Monitor". 97 | # - If not is_tech, check stock < 50; flag "Restock" or "Sufficient". 98 | # - Print the audit result. 99 | inventory = {"category": "Electronics", "price": 800, "stock": 25, "is_tech": True} 100 | if inventory["is_tech"]: 101 | if inventory["price"] > 700: 102 | if inventory["stock"] < 30: 103 | audit_result = "Critical" 104 | else: 105 | audit_result = "Monitor" 106 | else: 107 | audit_result = "Monitor" 108 | else: 109 | if inventory["stock"] < 50: 110 | audit_result = "Restock" 111 | else: 112 | audit_result = "Sufficient" 113 | print("Audit result:", audit_result) -------------------------------------------------------------------------------- /Core Python Foundations/02 Control Flow/04 For Loops/For Loops.py: -------------------------------------------------------------------------------- 1 | # Python Control Flow: For Loops 2 | # Purpose: Learn For Loops to iterate over sequences (lists, tuples, strings, etc.). 3 | # Key Features: Simplifies repetitive tasks over iterable objects. 4 | 5 | # %% 1. Basic For Loop 6 | # Explanation: Iterate over each element in a sequence, executing the loop body. 7 | # Ideal for processing collections. 8 | products = ["Laptop", "Smartphone", "Coffee Maker"] 9 | for product in products: 10 | print("1.1 Product:", product) 11 | # Example with string 12 | word = "Python" 13 | for char in word: 14 | print("1.2 Character:", char) 15 | 16 | # Mini-Exercise: Loop over a list of numbers and print each doubled. 17 | numbers = [1, 2, 3] 18 | for num in numbers: 19 | print("1.3 Mini-Exercise: Doubled:", num * 2) 20 | 21 | # %% 2. Using range() 22 | # Explanation: Generate numbers with range(start, stop, step) for controlled iteration. 23 | # Common for indexed operations or counters. 24 | for i in range(5): 25 | print(f"1.1 Item {i + 1}") 26 | # Example with step 27 | for i in range(0, 10, 2): 28 | print(f"1.2 Even number {i}") 29 | 30 | # Mini-Exercise: Print numbers from 1 to 3 using range(). 31 | for i in range(1, 4): 32 | print("2.3 Mini-Exercise: Number:", i) 33 | 34 | # %% 3. Iterating Over Dictionaries 35 | # Explanation: Loop over keys, values, or key-value pairs using .keys(), .values(), or .items(). 36 | # Useful for processing structured data. 37 | product = {"name": "Laptop Pro", "price": 999.99, "stock": 50} 38 | for key, value in product.items(): 39 | print(f"3.1 {key}: {value}") 40 | # Example with keys only 41 | for key in product: 42 | print(f"3.2 Key: {key}") 43 | 44 | # Mini-Exercise: Loop over a dictionary’s values and print each. 45 | for value in product.values(): 46 | print("3.3 Mini-Exercise: Value:", value) 47 | 48 | # %% 4. Exercises for Practice 49 | # Exercise 1: Loop over a list of prices and print each with a 10% discount. 50 | prices = [100, 200, 300] 51 | for price in prices: 52 | discounted = price * 0.9 53 | print("4.1 Exercise 1 - Discounted price:", discounted) 54 | 55 | # Exercise 2: Use range() to print the first 5 even numbers. 56 | for i in range(2, 11, 2): 57 | print("4.2 Exercise 2 - Even number:", i) 58 | 59 | # Exercise 3: Iterate over a dictionary of product details and print keys in uppercase. 60 | item = {"id": 1, "name": "Smartphone", "category": "Electronics"} 61 | for key in item: 62 | print("4.3 Exercise 3 - Uppercase key:", key.upper()) 63 | 64 | # Exercise 4: Loop over a list of products and print only those starting with 'S'. 65 | items = ["Smartphone", "Laptop", "Speaker", "Blender"] 66 | for item in items: 67 | if item.startswith("S"): 68 | print("4.4 Exercise 4 - Product starting with S:", item) 69 | 70 | # %% 5. Notes for Further Learning 71 | # - For loops are ideal for iterating over datasets in ML (e.g., feature processing) or web apps (e.g., rendering lists). 72 | # - Use enumerate() for index-element pairs (e.g., for i, item in enumerate(products)). 73 | # - Avoid modifying lists during iteration to prevent errors; use list comprehension for transformations. 74 | # - Combine with conditionals or break/continue for advanced control. 75 | # - Try the projects below to apply these concepts! -------------------------------------------------------------------------------- /Core Python Foundations/02 Control Flow/04 For Loops/forloops_projects.py: -------------------------------------------------------------------------------- 1 | # For Loops Projects 2 | # Purpose: Apply For Loops through 5 projects (Basic to Advanced). 3 | # Structure: Each project is separated by %% and includes description, tasks, and best solution. 4 | # Note: Solutions are designed for clarity, efficiency, and beginner learning. 5 | 6 | # %% Project 1: Price Formatter 7 | # Difficulty: Basic 8 | # Description: Format a list of prices with a discount. 9 | # Objective: Practice basic for loop over a list. 10 | # Tasks: 11 | # - Create a list of prices. 12 | # - Loop over prices and print each with a 5% discount. 13 | # - Print the discounted prices. 14 | prices = [100, 200, 300] 15 | for price in prices: 16 | discounted = price * 0.95 17 | print("Discounted price:", discounted) 18 | 19 | # %% Project 2: Product Counter 20 | # Difficulty: Basic 21 | # Description: Count products in a category. 22 | # Objective: Use for loop with conditionals. 23 | # Tasks: 24 | # - Create a list of product dictionaries with category. 25 | # - Loop over products and count those in "Electronics". 26 | # - Print the count. 27 | products = [ 28 | {"name": "Laptop", "category": "Electronics"}, 29 | {"name": "Blender", "category": "Appliances"}, 30 | {"name": "Smartphone", "category": "Electronics"} 31 | ] 32 | count = 0 33 | for product in products: 34 | if product["category"] == "Electronics": 35 | count += 1 36 | print("Electronics count:", count) 37 | 38 | # %% Project 3: Stock Summarizer 39 | # Difficulty: Intermediate 40 | # Description: Summarize stock levels across products. 41 | # Objective: Use for loop with dictionary iteration. 42 | # Tasks: 43 | # - Create a list of product dictionaries with stock. 44 | # - Loop over products and sum stock levels. 45 | # - Print the total stock. 46 | products = [ 47 | {"name": "Laptop", "stock": 50}, 48 | {"name": "Smartphone", "stock": 100}, 49 | {"name": "Blender", "stock": 0} 50 | ] 51 | total_stock = 0 52 | for product in products: 53 | total_stock += product["stock"] 54 | print("Total stock:", total_stock) 55 | 56 | # %% Project 4: Price Range Filter 57 | # Difficulty: Intermediate 58 | # Description: Filter products by price range. 59 | # Objective: Use for loop with conditionals and list creation. 60 | # Tasks: 61 | # - Create a list of product dictionaries with price. 62 | # - Loop over products and collect those with price > 500. 63 | # - Print the filtered products. 64 | products = [ 65 | {"name": "Laptop", "price": 999.99}, 66 | {"name": "Mouse", "price": 25}, 67 | {"name": "Smartphone", "price": 699.99} 68 | ] 69 | filtered = [] 70 | for product in products: 71 | if product["price"] > 500: 72 | filtered.append(product) 73 | print("Filtered products:", filtered) 74 | 75 | # %% Project 5: Order Report Generator 76 | # Difficulty: Advanced 77 | # Description: Generate a report for orders with dynamic formatting. 78 | # Objective: Use for loop with enumerate and string formatting. 79 | # Tasks: 80 | # - Create a list of order dictionaries with total and status. 81 | # - Loop over orders with enumerate to add index; format a report line for each. 82 | # - Print the report. 83 | orders = [ 84 | {"total": 1000, "status": "Shipped"}, 85 | {"total": 500, "status": "Pending"} 86 | ] 87 | for index, order in enumerate(orders, 1): 88 | print(f"Order {index}: Total ${order['total']:.2f}, Status: {order['status']}") -------------------------------------------------------------------------------- /Core Python Foundations/02 Control Flow/05 While Loops/While Loops.py: -------------------------------------------------------------------------------- 1 | # Python Control Flow: While Loops 2 | # Purpose: Learn While Loops to execute a block as long as a condition is True. 3 | # Key Features: Flexible for dynamic iteration, requires termination condition. 4 | 5 | # %% 1. Basic While Loop 6 | # Explanation: Continue looping until the condition becomes False. 7 | # Useful for tasks with unknown iteration counts. 8 | stock = 50 9 | while stock > 0: 10 | print(f"1.1 Stock remaining: {stock}") 11 | stock -= 10 12 | # Example with counter 13 | count = 1 14 | while count <= 3: 15 | print(f"1.2 Count: {count}") 16 | count += 1 17 | 18 | # Mini-Exercise: Reduce a price by 20 until it’s below 100. 19 | price = 150 20 | while price >= 100: 21 | print("1.3 Mini-Exercise: Price:", price) 22 | price -= 20 23 | 24 | # %% 2. While with Conditionals 25 | # Explanation: Combine with if-else for conditional logic within the loop. 26 | # Common in dynamic pricing or inventory adjustments. 27 | price = 1000 28 | discount = 0 29 | while price > 500: 30 | discount += 0.05 31 | price -= 100 32 | print(f"2.1 Price: {price}, Discount: {discount * 100}%") 33 | # Example with if 34 | stock_level = 80 35 | while stock_level > 20: 36 | if stock_level > 50: 37 | print(f"2.2 High stock: {stock_level}") 38 | else: 39 | print(f"2.2 Moderate stock: {stock_level}") 40 | stock_level -= 20 41 | 42 | # Mini-Exercise: Count up from 1 to 5, printing only odd numbers. 43 | num = 1 44 | while num <= 5: 45 | if num % 2 == 1: 46 | print("2.3 Mini-Exercise: Odd number:", num) 47 | num += 1 48 | 49 | # %% 3. Infinite Loop with Break 50 | # Explanation: Use break to exit an infinite loop based on a condition. 51 | # Useful for controlled termination. 52 | count = 0 53 | while True: 54 | count += 1 55 | if count > 3: 56 | print("3.1 Breaking at count:", count) 57 | break 58 | print(f"3.1 Count: {count}") 59 | # Example with condition 60 | total = 0 61 | while True: 62 | total += 10 63 | if total >= 50: 64 | print(f"3.2 Total reached: {total}") 65 | break 66 | 67 | # Mini-Exercise: Increment a counter until it reaches 4, then break. 68 | counter = 0 69 | while True: 70 | counter += 1 71 | if counter >= 4: 72 | print("3.3 Mini-Exercise: Stopped at:", counter) 73 | break 74 | print("3.3 Mini-Exercise: Counter:", counter) 75 | 76 | # %% 4. Exercises for Practice 77 | # Exercise 1: Use a while loop to reduce a product’s price by 50 until it’s below 200. 78 | price = 500 79 | while price >= 200: 80 | price -= 50 81 | print("4.1 Exercise 1 - Reduced price:", price) 82 | 83 | # Exercise 2: Count down from 10 to 1 using a while loop. 84 | num = 10 85 | while num >= 1: 86 | print("4.2 Exercise 2 - Countdown:", num) 87 | num -= 1 88 | 89 | # Exercise 3: Use a while loop to find the first stock level below 30, starting from 100. 90 | stock = 100 91 | while stock >= 30: 92 | stock -= 10 93 | print("4.3 Exercise 3 - First stock below 30:", stock) 94 | 95 | # Exercise 4: Double a value starting from 1 until it exceeds 100. 96 | value = 1 97 | while value <= 100: 98 | value *= 2 99 | print("4.4 Exercise 4 - Value:", value) 100 | 101 | # %% 5. Notes for Further Learning 102 | # - Ensure while loops have a clear termination condition to avoid infinite loops. 103 | # - Use in ML for iterative algorithms (e.g., gradient descent) or web apps for polling. 104 | # - Combine with break/continue for fine-grained control (see later subtopics). 105 | # - Test loop conditions to ensure all cases are handled. 106 | # - Try the projects below to apply these concepts! -------------------------------------------------------------------------------- /Core Python Foundations/02 Control Flow/05 While Loops/whileloops_projects.py: -------------------------------------------------------------------------------- 1 | # While Loops Projects 2 | # Purpose: Apply While Loops through 5 projects (Basic to Advanced). 3 | # Structure: Each project is separated by %% and includes description, tasks, and best solution. 4 | # Note: Solutions are designed for clarity, efficiency, and beginner learning. 5 | 6 | # %% Project 1: Price Reducer 7 | # Difficulty: Basic 8 | # Description: Reduce a price until affordable. 9 | # Objective: Practice basic while loop with decrement. 10 | # Tasks: 11 | # - Create a variable for price. 12 | # - While price > 200, reduce by 50 and print. 13 | # - Print the final price. 14 | price = 500 15 | while price > 200: 16 | price -= 50 17 | print("Reduced price:", price) 18 | print("Final price:", price) 19 | 20 | # %% Project 2: Stock Depletion Tracker 21 | # Difficulty: Basic 22 | # Description: Track stock depletion over time. 23 | # Objective: Use while loop with conditionals. 24 | # Tasks: 25 | # - Create a variable for stock. 26 | # - While stock > 0, reduce by 10 and print status. 27 | # - Print final stock. 28 | stock = 100 29 | while stock > 0: 30 | stock -= 10 31 | print("Stock:", stock) 32 | print("Final stock:", stock) 33 | 34 | # %% Project 3: Order Accumulator 35 | # Difficulty: Intermediate 36 | # Description: Accumulate order totals until a threshold. 37 | # Objective: Use while loop with list processing. 38 | # Tasks: 39 | # - Create a list of order amounts. 40 | # - While total < 1000, add next amount and print running total. 41 | # - Print final total. 42 | orders = [300, 300, 500] 43 | total = 0 44 | index = 0 45 | while total < 1000 and index < len(orders): 46 | total += orders[index] 47 | print("Running total:", total) 48 | index += 1 49 | print("Final total:", total) 50 | 51 | # %% Project 4: Discount Optimizer 52 | # Difficulty: Intermediate 53 | # Description: Optimize discounts to reach a target price. 54 | # Objective: Use while loop with dynamic adjustments. 55 | # Tasks: 56 | # - Create variables for price and target. 57 | # - While price > target, increase discount by 5% and print new price. 58 | # - Print final discount. 59 | price = 1000 60 | target = 850 61 | discount = 0 62 | while price > target: 63 | discount += 0.05 64 | price = 1000 * (1 - discount) 65 | print("New price:", price) 66 | print("Final discount:", f"{discount * 100}%") 67 | 68 | # %% Project 5: Inventory Restock Simulator 69 | # Difficulty: Advanced 70 | # Description: Simulate restocking until sufficient. 71 | # Objective: Use while loop with complex logic. 72 | # Tasks: 73 | # - Create a dictionary with stock and target. 74 | # - While stock < target, add 10 units if stock < 50, else 5; track restocks. 75 | # - Print restock count and final stock. 76 | inventory = {"stock": 30, "target": 100} 77 | restock_count = 0 78 | while inventory["stock"] < inventory["target"]: 79 | if inventory["stock"] < 50: 80 | inventory["stock"] += 10 81 | else: 82 | inventory["stock"] += 5 83 | restock_count += 1 84 | print("Restock count:", restock_count) 85 | print("Final stock:", inventory["stock"]) -------------------------------------------------------------------------------- /Core Python Foundations/02 Control Flow/06 Break Statement/Break Statement.py: -------------------------------------------------------------------------------- 1 | # Python Control Flow: Break Statement 2 | # Purpose: Learn Break Statement to exit a loop immediately. 3 | # Key Features: Terminates loop execution based on a condition, enables early stopping. 4 | 5 | # %% 1. Break in For Loop 6 | # Explanation: Exit a for loop when a condition is met, skipping remaining iterations. 7 | # Useful for searching or thresholding. 8 | prices = [100, 200, 999.99, 50, 300] 9 | for price in prices: 10 | if price > 500: 11 | print(f"1.1 Found expensive item: {price}, stopping") 12 | break 13 | print(f"1.1 Price: {price}") 14 | # Example with list 15 | items = ["Mouse", "Keyboard", "Monitor"] 16 | for item in items: 17 | if item == "Keyboard": 18 | print(f"1.2 Found {item}, stopping") 19 | break 20 | print(f"1.2 Checking: {item}") 21 | 22 | # Mini-Exercise: Stop a for loop when a number exceeds 5. 23 | numbers = [2, 4, 6, 8] 24 | for num in numbers: 25 | if num > 5: 26 | print("1.3 Mini-Exercise: Number too large:", num) 27 | break 28 | print("1.3 Mini-Exercise: Number:", num) 29 | 30 | # %% 2. Break in While Loop 31 | # Explanation: Exit a while loop to prevent infinite or unwanted iterations. 32 | # Common in dynamic processes. 33 | stock = 100 34 | while stock > 0: 35 | if stock < 50: 36 | print(f"2.1 Stock too low: {stock}, stopping") 37 | break 38 | stock -= 20 39 | print(f"2.1 Stock: {stock}") 40 | # Example with counter 41 | count = 0 42 | while count < 10: 43 | count += 1 44 | if count == 5: 45 | print(f"2.2 Stopping at count: {count}") 46 | break 47 | print(f"2.2 Count: {count}") 48 | 49 | # Mini-Exercise: Break a while loop when a price falls below 200. 50 | price = 300 51 | while price > 100: 52 | if price < 200: 53 | print("2.3 Mini-Exercise: Price too low:", price) 54 | break 55 | price -= 50 56 | print("2.3 Mini-Exercise: Price:", price) 57 | 58 | # %% 3. Break in Nested Loops 59 | # Explanation: Break exits only the innermost loop; outer loops continue. 60 | # Useful for multi-level searches. 61 | products = ["Laptop", "Smartphone", "Coffee Maker"] 62 | categories = ["Electronics", "Appliances"] 63 | for product in products: 64 | for category in categories: 65 | if product == "Coffee Maker" and category == "Appliances": 66 | print(f"3.1 Found {product} in {category}, stopping") 67 | break 68 | print(f"3.1 Checking {product} in {category}") 69 | # Example with dictionary 70 | items = [{"name": "Laptop", "price": 999}, {"name": "Mouse", "price": 25}] 71 | for item in items: 72 | for key, value in item.items(): 73 | if item["price"] > 500: 74 | print(f"3.2 Expensive item: {item['name']}, stopping") 75 | break 76 | print(f"3.2 Checking {key}: {value}") 77 | 78 | # Mini-Exercise: Break a nested loop when a value exceeds 10. 79 | outer = [1, 2] 80 | inner = [5, 15, 20] 81 | for x in outer: 82 | for y in inner: 83 | if y > 10: 84 | print("3.3 Mini-Exercise: Value too large:", y) 85 | break 86 | print("3.3 Mini-Exercise: Value:", y) 87 | 88 | # %% 4. Exercises for Practice 89 | # Exercise 1: Stop a for loop over a list of quantities when a quantity exceeds 10. 90 | quantities = [5, 8, 12, 3] 91 | for qty in quantities: 92 | if qty > 10: 93 | print("4.1 Exercise 1 - High quantity found:", qty) 94 | break 95 | print("4.1 Exercise 1 - Quantity:", qty) 96 | 97 | # Exercise 2: Use break in a while loop to stop when price falls below 300. 98 | price = 500 99 | while price > 0: 100 | if price < 300: 101 | print("4.2 Exercise 2 - Price below 300:", price) 102 | break 103 | price -= 50 104 | print("4.2 Exercise 2 - Price:", price) 105 | 106 | # Exercise 3: Break a nested loop when a product’s price and stock meet criteria (price > 700, stock < 50). 107 | items = [{"name": "Laptop", "price": 999.99, "stock": 30}, 108 | {"name": "Smartphone", "price": 699.99, "stock": 100}] 109 | for item in items: 110 | for key, value in item.items(): 111 | if item["price"] > 700 and item["stock"] < 50: 112 | print("4.3 Exercise 3 - Criteria met for", item["name"]) 113 | break 114 | print("4.3 Exercise 3 - Checking", key, value) 115 | 116 | # Exercise 4: Break a for loop when a string contains "phone". 117 | words = ["Laptop", "Smartphone", "Tablet"] 118 | for word in words: 119 | if "phone" in word.lower(): 120 | print("4.4 Exercise 4 - Found phone in:", word) 121 | break 122 | print("4.4 Exercise 4 - Checking:", word) 123 | 124 | # %% 5. Notes for Further Learning 125 | # - Break exits only the innermost loop; use flags or multiple breaks for outer loops. 126 | # - Use in ML for early stopping (e.g., training loops) or web apps for search termination. 127 | # - Combine with conditionals for precise control, but avoid overuse to maintain clarity. 128 | # - Test break conditions to ensure loops terminate as expected. 129 | # - Try the projects below to apply these concepts! -------------------------------------------------------------------------------- /Core Python Foundations/02 Control Flow/06 Break Statement/break_projects.py: -------------------------------------------------------------------------------- 1 | # Break Projects 2 | # Purpose: Apply Break Statement through 5 projects (Basic to Advanced). 3 | # Structure: Each project is separated by %% and includes description, tasks, and best solution. 4 | # Note: Solutions are designed for clarity, efficiency, and beginner learning. 5 | 6 | # %% Project 1: Price Threshold Stopper 7 | # Difficulty: Basic 8 | # Description: Stop processing prices when too high. 9 | # Objective: Practice break in for loop. 10 | # Tasks: 11 | # - Create a list of prices. 12 | # - Loop over prices; break if price > 1000. 13 | # - Print processed prices. 14 | prices = [200, 500, 1200, 300] 15 | for price in prices: 16 | if price > 1000: 17 | print("Stopped at:", price) 18 | break 19 | print("Processed price:", price) 20 | 21 | # %% Project 2: Stock Limit Checker 22 | # Difficulty: Basic 23 | # Description: Stop checking stock when too low. 24 | # Objective: Use break in while loop. 25 | # Tasks: 26 | # - Create a variable for stock. 27 | # - While stock > 0, reduce by 20; break if < 30. 28 | # - Print final stock. 29 | stock = 100 30 | while stock > 0: 31 | stock -= 20 32 | print("Stock:", stock) 33 | if stock < 30: 34 | print("Stopped at:", stock) 35 | break 36 | 37 | # %% Project 3: Product Searcher 38 | # Difficulty: Intermediate 39 | # Description: Search for a specific product in a list. 40 | # Objective: Use break with for loop and conditionals. 41 | # Tasks: 42 | # - Create a list of product dictionaries. 43 | # - Loop over products; break when Electronics with price > 500 is found. 44 | # - Print found product or "Not found". 45 | products = [ 46 | {"name": "Mouse", "category": "Electronics", "price": 25}, 47 | {"name": "Laptop", "category": "Electronics", "price": 999.99}, 48 | {"name": "Blender", "category": "Appliances", "price": 100} 49 | ] 50 | found = None 51 | for product in products: 52 | if product["category"] == "Electronics" and product["price"] > 500: 53 | found = product 54 | break 55 | print("Found product:", found if found else "Not found") 56 | 57 | # %% Project 4: Order Scanner 58 | # Difficulty: Intermediate 59 | # Description: Scan orders until a large order is found. 60 | # Objective: Use break with while loop and list. 61 | # Tasks: 62 | # - Create a list of order totals. 63 | # - While iterating, break if total > 2000. 64 | # - Print processed totals and stopping point. 65 | orders = [500, 1000, 2500, 300] 66 | index = 0 67 | while index < len(orders): 68 | total = orders[index] 69 | if total > 2000: 70 | print("Stopped at:", total) 71 | break 72 | print("Processed total:", total) 73 | index += 1 74 | 75 | # %% Project 5: Nested Product Filter 76 | # Difficulty: Advanced 77 | # Description: Filter products in nested loops with early stopping. 78 | # Objective: Use break in nested loops with complex data. 79 | # Tasks: 80 | # - Create a list of product dictionaries with attributes. 81 | # - Loop over products and attributes; break inner loop if price > 700 and stock < 50. 82 | # - Print filtered products. 83 | products = [ 84 | {"name": "Laptop", "price": 999.99, "stock": 30}, 85 | {"name": "Smartphone", "price": 699.99, "stock": 100} 86 | ] 87 | filtered = [] 88 | for product in products: 89 | for key, value in product.items(): 90 | if product["price"] > 700 and product["stock"] < 50: 91 | filtered.append(product) 92 | break 93 | print("Filtered product:", filtered) -------------------------------------------------------------------------------- /Core Python Foundations/02 Control Flow/07 Continue Statement/Continue Statement.py: -------------------------------------------------------------------------------- 1 | # Python Control Flow: Continue Statement 2 | # Purpose: Learn Continue Statement to skip the rest of the current loop iteration. 3 | # Key Features: Selective iteration control, skips to next iteration. 4 | 5 | # %% 1. Continue in For Loop 6 | # Explanation: Skip the current iteration when a condition is met, continue with next item. 7 | # Useful for filtering during iteration. 8 | prices = [100, 999.99, 50, 700, 25] 9 | for price in prices: 10 | if price < 100: 11 | continue 12 | print(f"1.1 Price above 100: {price}") 13 | # Example with strings 14 | items = ["Mouse", "Keyboard", "Monitor"] 15 | for item in items: 16 | if len(item) < 6: 17 | continue 18 | print(f"1.2 Long name: {item}") 19 | 20 | # Mini-Exercise: Skip numbers less than 3 in a for loop. 21 | numbers = [1, 3, 5] 22 | for num in numbers: 23 | if num < 3: 24 | continue 25 | print("1.3 Mini-Exercise: Number:", num) 26 | 27 | # %% 2. Continue in While Loop 28 | # Explanation: Skip iteration in a while loop, re-evaluate the condition. 29 | # Common in dynamic filtering. 30 | stock = 100 31 | while stock > 0: 32 | stock -= 20 33 | if stock % 40 == 0: 34 | continue 35 | print(f"2.1 Stock level: {stock}") 36 | # Example with counter 37 | count = 0 38 | while count < 5: 39 | count += 1 40 | if count % 2 == 0: 41 | continue 42 | print(f"2.2 Odd count: {count}") 43 | 44 | # Mini-Exercise: Skip stock levels divisible by 30 in a while loop. 45 | stock = 90 46 | while stock > 0: 47 | stock -= 10 48 | if stock % 30 == 0: 49 | continue 50 | print("2.3 Mini-Exercise: Stock:", stock) 51 | 52 | # %% 3. Continue in Nested Loops 53 | # Explanation: Skips only the innermost loop’s current iteration; outer loop continues. 54 | # Useful for selective processing in multi-level loops. 55 | products = ["Laptop", "Smartphone", "Coffee Maker"] 56 | categories = ["Electronics", "Appliances"] 57 | for product in products: 58 | for category in categories: 59 | if category == "Appliances": 60 | continue 61 | print(f"3.1 Checking {product} in {category}") 62 | # Example with dictionary 63 | items = [{"name": "Laptop", "category": "Electronics"}, 64 | {"name": "Blender", "category": "Appliances"}] 65 | for item in items: 66 | for key, value in item.items(): 67 | if item["category"] != "Electronics": 68 | continue 69 | print(f"3.2 Electronics attribute: {key} = {value}") 70 | 71 | # Mini-Exercise: Skip inner loop values less than 10 in a nested loop. 72 | outer = [1, 2] 73 | inner = [5, 15, 20] 74 | for x in outer: 75 | for y in inner: 76 | if y < 10: 77 | continue 78 | print("3.3 Mini-Exercise: Value:", y) 79 | 80 | # %% 4. Exercises for Practice 81 | # Exercise 1: Skip prices below 200 in a for loop over a list of prices. 82 | prices = [150, 300, 50, 400] 83 | for price in prices: 84 | if price < 200: 85 | continue 86 | print("4.1 Exercise 1 - Price:", price) 87 | 88 | # Exercise 2: Use continue in a while loop to skip stock levels that are even. 89 | stock = 50 90 | while stock > 0: 91 | stock -= 10 92 | if stock % 2 == 0: 93 | continue 94 | print("4.2 Exercise 2 - Odd stock level:", stock) 95 | 96 | # Exercise 3: Skip non-Electronics products in a nested loop over products and attributes. 97 | items = [{"name": "Laptop", "category": "Electronics"}, 98 | {"name": "Blender", "category": "Appliances"}] 99 | for item in items: 100 | for key, value in item.items(): 101 | if item["category"] != "Electronics": 102 | continue 103 | print("4.3 Exercise 3 - Electronics attribute:", key, value) 104 | 105 | # Exercise 4: Skip words shorter than 5 characters in a for loop. 106 | words = ["Cat", "Mouse", "Keyboard"] 107 | for word in words: 108 | if len(word) < 5: 109 | continue 110 | print("4.4 Exercise 4 - Long word:", word) 111 | 112 | # %% 5. Notes for Further Learning 113 | # - Continue skips to the next iteration without exiting the loop, useful for filtering. 114 | # - Use in ML for data preprocessing (e.g., skipping invalid entries) or web apps for selective processing. 115 | # - Avoid overusing continue to maintain code clarity; consider list comprehensions for simple filters. 116 | # - Test continue conditions to ensure correct iterations are skipped. 117 | # - Try the projects below to apply these concepts! -------------------------------------------------------------------------------- /Core Python Foundations/02 Control Flow/07 Continue Statement/continue_projects.py: -------------------------------------------------------------------------------- 1 | # Continue Projects 2 | # Purpose: Apply Continue Statement through 5 projects (Basic to Advanced). 3 | # Structure: Each project is separated by %% and includes description, tasks, and best solution. 4 | # Note: Solutions are designed for clarity, efficiency, and beginner learning. 5 | 6 | # %% Project 1: Price Filter 7 | # Difficulty: Basic 8 | # Description: Filter out low prices during processing. 9 | # Objective: Practice continue in for loop. 10 | # Tasks: 11 | # - Create a list of prices. 12 | # - Loop over prices; skip if price < 200. 13 | # - Print valid prices. 14 | prices = [150, 300, 50, 500] 15 | for price in prices: 16 | if price < 200: 17 | continue 18 | print("Valid price:", price) 19 | 20 | # %% Project 2: Stock Skip System 21 | # Difficulty: Basic 22 | # Description: Skip even stock levels during depletion. 23 | # Objective: Use continue in while loop. 24 | # Tasks: 25 | # - Create a variable for stock. 26 | # - While stock > 0, reduce by 10; skip even levels. 27 | # - Print odd stock levels. 28 | stock = 100 29 | while stock > 0: 30 | stock -= 10 31 | if stock % 2 == 0: 32 | continue 33 | print("Odd stock level:", stock) 34 | 35 | # %% Project 3: Category Processor 36 | # Difficulty: Intermediate 37 | # Description: Process only specific product categories. 38 | # Objective: Use continue with for loop and dictionaries. 39 | # Tasks: 40 | # - Create a list of product dictionaries with category. 41 | # - Loop over products; skip non-Electronics. 42 | # - Print processed products. 43 | products = [ 44 | {"name": "Laptop", "category": "Electronics"}, 45 | {"name": "Blender", "category": "Appliances"}, 46 | {"name": "Smartphone", "category": "Electronics"} 47 | ] 48 | for product in products: 49 | if product["category"] != "Electronics": 50 | continue 51 | print("Processed product:", product) 52 | 53 | # %% Project 4: Order Skipper 54 | # Difficulty: Intermediate 55 | # Description: Skip small orders during processing. 56 | # Objective: Use continue with while loop and list. 57 | # Tasks: 58 | # - Create a list of order totals. 59 | # - While iterating, skip totals < 500. 60 | # - Print processed totals. 61 | orders = [200, 1000, 300, 2000] 62 | index = 0 63 | while index < len(orders): 64 | total = orders[index] 65 | if total < 500: 66 | index += 1 67 | continue 68 | print("Processed total:", total) 69 | index += 1 70 | 71 | # %% Project 5: Nested Attribute Filter 72 | # Difficulty: Advanced 73 | # Description: Filter attributes in nested loops. 74 | # Objective: Use continue in nested loops with complex data. 75 | # Tasks: 76 | # - Create a list of product dictionaries with attributes. 77 | # - Loop over products and attributes; skip if category isn’t Electronics. 78 | # - Print Electronics attributes. 79 | products = [ 80 | {"name": "Laptop", "category": "Electronics"}, 81 | {"name": "Blender", "category": "Appliances"} 82 | ] 83 | for product in products: 84 | for key, value in product.items(): 85 | if product["category"] != "Electronics": 86 | continue 87 | print(f"Electronics attribute: {key} = {value}") -------------------------------------------------------------------------------- /Core Python Foundations/02 Control Flow/08 Pass Statement/Pass Statement.py: -------------------------------------------------------------------------------- 1 | # Python Control Flow: Pass Statement 2 | # Purpose: Learn Pass Statement as a placeholder that does nothing. 3 | # Key Features: Enables empty blocks during development, ensures syntactical completeness. 4 | 5 | # %% 1. Pass in Conditionals 6 | # Explanation: Use pass when a block is required but no action is needed yet. 7 | # Common during initial development or prototyping. 8 | price = 999.99 9 | if price > 1000: 10 | print("1.1 Luxury product") 11 | else: 12 | pass # Placeholder for future logic 13 | # Example with multiple conditions 14 | stock = 50 15 | if stock < 20: 16 | print("1.2 Low stock") 17 | else: 18 | pass # To be implemented 19 | 20 | # Mini-Exercise: Use pass for prices above 500. 21 | test_price = 400 22 | if test_price > 500: 23 | pass 24 | else: 25 | print("1.3 Mini-Exercise: Price below 500:", test_price) 26 | 27 | # %% 2. Pass in Loops 28 | # Explanation: Use pass in loops to skip implementation temporarily. 29 | # Useful for outlining loop structure. 30 | products = ["Laptop", "Smartphone", "Coffee Maker"] 31 | for product in products: 32 | if product == "Smartphone": 33 | pass # Will add logic later 34 | else: 35 | print(f"2.1 Processing {product}") 36 | # Example with while 37 | count = 0 38 | while count < 3: 39 | count += 1 40 | if count == 2: 41 | pass 42 | else: 43 | print(f"2.2 Count: {count}") 44 | 45 | # Mini-Exercise: Use pass for odd numbers in a for loop. 46 | numbers = [1, 2, 3] 47 | for num in numbers: 48 | if num % 2 == 1: 49 | pass 50 | else: 51 | print("2.3 Mini-Exercise: Even number:", num) 52 | 53 | # %% 3. Pass in Functions or Classes 54 | # Explanation: Use pass for unimplemented functions or class methods. 55 | # Common in API design or class scaffolding. 56 | def calculate_discount(price): 57 | pass # To be implemented later 58 | class Product: 59 | def update_stock(self): 60 | pass # Placeholder for method 61 | product = Product() 62 | print("3.1 Created Product object (no action)") 63 | # Example with function 64 | def process_order(order): 65 | pass 66 | print("3.2 Placeholder function defined") 67 | 68 | # Mini-Exercise: Define a placeholder class with a pass method. 69 | class Order: 70 | def cancel(self): 71 | pass 72 | order = Order() 73 | print("3.3 Mini-Exercise: Order class defined") 74 | 75 | # %% 4. Exercises for Practice 76 | # Exercise 1: Use pass in an if-else block to skip budget products (< 100). 77 | price = 50 78 | if price < 100: 79 | pass 80 | else: 81 | print("4.1 Exercise 1 - Non-budget price:", price) 82 | 83 | # Exercise 2: Use pass in a for loop to skip a specific product. 84 | items = ["Mouse", "Keyboard", "Monitor"] 85 | for item in items: 86 | if item == "Keyboard": 87 | pass 88 | else: 89 | print("4.2 Exercise 2 - Processing:", item) 90 | 91 | # Exercise 3: Define a placeholder function for stock checking with pass. 92 | def check_stock(stock): 93 | pass 94 | print("4.3 Exercise 3 - Placeholder function defined") 95 | 96 | # Exercise 4: Use pass in a while loop for stock levels above 50. 97 | stock = 70 98 | while stock > 0: 99 | stock -= 10 100 | if stock > 50: 101 | pass 102 | else: 103 | print("4.4 Exercise 4 - Stock level:", stock) 104 | 105 | # %% 5. Notes for Further Learning 106 | # - Pass is a no-op, used to avoid syntax errors during development. 107 | # - Common in ML for placeholder model training functions or web apps for API stubs. 108 | # - Replace pass with actual logic as development progresses. 109 | # - Use sparingly; excessive pass statements may indicate incomplete design. 110 | # - Try the projects below to apply these concepts! -------------------------------------------------------------------------------- /Core Python Foundations/02 Control Flow/08 Pass Statement/pass_projects.py: -------------------------------------------------------------------------------- 1 | # Pass Projects 2 | # Purpose: Apply Pass Statement through 5 projects (Basic to Advanced). 3 | # Structure: Each project is separated by %% and includes description, tasks, and best solution. 4 | # Note: Solutions are designed for clarity, efficiency, and beginner learning. 5 | 6 | # %% Project 1: Price Placeholder 7 | # Difficulty: Basic 8 | # Description: Placeholder for price processing logic. 9 | # Objective: Practice pass in if-else. 10 | # Tasks: 11 | # - Create a variable for price. 12 | # - If price > 500, pass; else print "Budget price". 13 | # - Print a completion message. 14 | price = 400 15 | if price > 500: 16 | pass 17 | else: 18 | print("Budget price:", price) 19 | print("Processing complete") 20 | 21 | # %% Project 2: Product Skip Placeholder 22 | # Difficulty: Basic 23 | # Description: Placeholder for specific product processing. 24 | # Objective: Use pass in for loop. 25 | # Tasks: 26 | # - Create a list of products. 27 | # - Loop over products; pass for "Smartphone", print others. 28 | # - Print processed products. 29 | products = ["Laptop", "Smartphone", "Coffee Maker"] 30 | for product in products: 31 | if product == "Smartphone": 32 | pass 33 | else: 34 | print("Processed product:", product) 35 | 36 | # %% Project 3: Stock Placeholder 37 | # Difficulty: Intermediate 38 | # Description: Placeholder for stock level checks. 39 | # Objective: Use pass in while loop. 40 | # Tasks: 41 | # - Create a variable for stock. 42 | # - While stock > 0, pass if stock > 50; else print level. 43 | # - Print final stock. 44 | stock = 70 45 | while stock > 0: 46 | stock -= 10 47 | if stock > 50: 48 | pass 49 | else: 50 | print("Stock level:", stock) 51 | print("Final stock:", stock) 52 | 53 | # %% Project 4: Category Placeholder 54 | # Difficulty: Intermediate 55 | # Description: Placeholder for category-specific logic. 56 | # Objective: Use pass with dictionary iteration. 57 | # Tasks: 58 | # - Create a list of product dictionaries. 59 | # - Loop over products; pass for Electronics, print others. 60 | # - Print processed products. 61 | products = [ 62 | {"name": "Laptop", "category": "Electronics"}, 63 | {"name": "Blender", "category": "Appliances"} 64 | ] 65 | for product in products: 66 | if product["category"] == "Electronics": 67 | pass 68 | else: 69 | print("Processed product:", product) 70 | 71 | # %% Project 5: Function Stub System 72 | # Difficulty: Advanced 73 | # Description: Create placeholder functions for order processing. 74 | # Objective: Use pass in functions with control flow. 75 | # Tasks: 76 | # - Define a function to process orders with pass for totals > 1000. 77 | # - Call function with a list of orders and print processed orders. 78 | # - Print completion message. 79 | def process_orders(orders): 80 | for total in orders: 81 | if total > 1000: 82 | pass 83 | else: 84 | print("Processed order:", total) 85 | orders = [500, 1500, 300] 86 | process_orders(orders) 87 | print("Processing complete") -------------------------------------------------------------------------------- /Core Python Foundations/04 Comprehensions/01 List Comprehensions/List Comprehensions.py: -------------------------------------------------------------------------------- 1 | # %% Purpose 2 | # Python Comprehensions: List Comprehensions 3 | # Purpose: List comprehensions provide a concise way to create lists using a single line of code. 4 | # Key Features: Compact syntax, readable, combines loops and conditionals. 5 | 6 | # %% 1. Basic List Comprehension 7 | # Explanation: Create a list from an iterable using [expression for item in iterable]. 8 | # Example: 9 | prices = [100, 200, 300, 400] 10 | discounted_prices = [price * 0.9 for price in prices] 11 | print("Discounted prices:", discounted_prices) 12 | # Output: Discounted prices: [90.0, 180.0, 270.0, 360.0] 13 | 14 | # %% 2. List Comprehension with Condition 15 | # Explanation: Include only items meeting a condition using [expression for item in iterable if condition]. 16 | # Example: 17 | products = ["Laptop", "Smartphone", "Coffee Maker", "Blender"] 18 | electronics = [product for product in products if "phone" in product.lower() or "laptop" in product.lower()] 19 | print("Electronics products:", electronics) 20 | # Output: Electronics products: ['Laptop', 'Smartphone'] 21 | 22 | # %% 3. Nested List Comprehension 23 | # Explanation: Use nested loops within a comprehension for complex transformations. 24 | # Example: 25 | categories = ["Electronics", "Appliances"] 26 | items = ["Laptop", "Blender"] 27 | product_pairs = [f"{item} ({cat})" for cat in categories for item in items] 28 | print("Product pairs:", product_pairs) 29 | # Output: Product pairs: ['Laptop (Electronics)', 'Blender (Electronics)', 'Laptop (Appliances)', 'Blender (Appliances)'] 30 | 31 | # %% Notes 32 | # Notes: 33 | # - List comprehensions are faster than equivalent for loops but can reduce readability if overused. 34 | # - Use in ML for data preprocessing (e.g., filtering features) or web apps for generating lists (e.g., product displays). 35 | # - Avoid complex nested comprehensions; use regular loops for clarity if needed. -------------------------------------------------------------------------------- /Core Python Foundations/04 Comprehensions/02 Dictionary Comprehensions/Dictionary Comprehensions.py: -------------------------------------------------------------------------------- 1 | # %% Purpose 2 | # Python Comprehensions: Dictionary Comprehensions 3 | # Purpose: Dictionary comprehensions create dictionaries concisely using a single line. 4 | # Key Features: Generates key-value pairs, supports conditionals. 5 | 6 | # %% 1. Basic Dictionary Comprehension 7 | # Explanation: Create a dictionary using {key_expr: value_expr for item in iterable}. 8 | # Example: 9 | products = ["Laptop", "Smartphone", "Coffee Maker"] 10 | product_ids = {name: idx + 1 for idx, name in enumerate(products)} 11 | print("Product IDs:", product_ids) 12 | # Output: Product IDs: {'Laptop': 1, 'Smartphone': 2, 'Coffee Maker': 3} 13 | 14 | # %% 2. Dictionary Comprehension with Condition 15 | # Explanation: Filter items with [key_expr: value_expr for item in iterable if condition]. 16 | # Example: 17 | prices = {"Laptop": 999.99, "Smartphone": 699.99, "Coffee Maker": 49.99} 18 | expensive_items = {name: price for name, price in prices.items() if price > 500} 19 | print("Expensive items:", expensive_items) 20 | # Output: Expensive items: {'Laptop': 999.99, 'Smartphone': 699.99} 21 | 22 | # %% 3. Transforming Keys or Values 23 | # Explanation: Modify keys or values during creation (e.g., formatting, calculations). 24 | # Example: 25 | stock = {"Laptop": 50, "Smartphone": 100, "Blender": 20} 26 | stock_status = {f"{name}_stock": "Low" if qty < 50 else "Sufficient" for name, qty in stock.items()} 27 | print("Stock status:", stock_status) 28 | # Output: Stock status: {'Laptop_stock': 'Sufficient', 'Smartphone_stock': 'Sufficient', 'Blender_stock': 'Low'} 29 | 30 | # %% Notes 31 | # Notes: 32 | # - Dictionary comprehensions are efficient for creating key-value mappings in ML (e.g., feature dictionaries) or web apps (e.g., API responses). 33 | # - Ensure keys are unique and hashable (e.g., strings, numbers, tuples). 34 | # - Use sparingly for complex logic to maintain readability. -------------------------------------------------------------------------------- /Core Python Foundations/04 Comprehensions/03 Set Comprehensions/Set Comprehensions.py: -------------------------------------------------------------------------------- 1 | # %% Purpose 2 | # Python Comprehensions: Set Comprehensions 3 | # Purpose: Set comprehensions create sets concisely, ensuring unique elements. 4 | # Key Features: Eliminates duplicates, supports conditionals. 5 | 6 | # %% 1. Basic Set Comprehension 7 | # Explanation: Create a set using {expression for item in iterable}. 8 | # Example: 9 | products = ["Laptop", "Smartphone", "Laptop", "Coffee Maker"] 10 | unique_products = {product for product in products} 11 | print("Unique products:", unique_products) 12 | # Output: Unique products: {'Laptop', 'Smartphone', 'Coffee Maker'} 13 | 14 | # %% 2. Set Comprehension with Condition 15 | # Explanation: Filter items with {expression for item in iterable if condition}. 16 | # Example: 17 | prices = [100, 200, 150, 999.99, 200] 18 | high_prices = {price for price in prices if price > 500} 19 | print("High prices:", high_prices) 20 | # Output: High prices: {999.99} 21 | 22 | # %% 3. Transforming Elements 23 | # Explanation: Apply transformations to elements during set creation. 24 | # Example: 25 | categories = ["Electronics", "Appliances", "Electronics", "Furniture"] 26 | upper_categories = {cat.upper() for cat in categories} 27 | print("Uppercase categories:", upper_categories) 28 | # Output: Uppercase categories: {'ELECTRONICS', 'APPLIANCES', 'FURNITURE'} 29 | 30 | # %% Notes 31 | # Notes: 32 | # - Set comprehensions automatically remove duplicates, useful in ML for unique labels or web apps for unique tags. 33 | # - Sets are unordered; use lists if order matters. 34 | # - Keep comprehensions simple to avoid readability issues. -------------------------------------------------------------------------------- /Core Python Foundations/04 Comprehensions/04 Generator Expressions/Generator Expressions.py: -------------------------------------------------------------------------------- 1 | # %% Purpose 2 | # Python Comprehensions: Generator Expressions 3 | # Purpose: Generator expressions create iterators lazily, yielding items one at a time. 4 | # Key Features: Memory-efficient, single-use iteration. 5 | 6 | # %% 1. Basic Generator Expression 7 | # Explanation: Use (expression for item in iterable) to create a generator. 8 | # Example: 9 | prices = [100, 200, 300, 400] 10 | discounted_gen = (price * 0.9 for price in prices) 11 | print("Generator object:", discounted_gen) 12 | # Convert to list for display 13 | discounted_list = list(discounted_gen) 14 | print("Discounted prices:", discounted_list) 15 | # Output: Generator object: , Discounted prices: [90.0, 180.0, 270.0, 360.0] 16 | 17 | # %% 2. Generator with Condition 18 | # Explanation: Filter items with (expression for item in iterable if condition). 19 | # Example: 20 | products = ["Laptop", "Smartphone", "Coffee Maker", "Blender"] 21 | electronics_gen = (product for product in products if "phone" in product.lower() or "laptop" in product.lower()) 22 | print("Electronics (generator):", list(electronics_gen)) 23 | # Output: Electronics (generator): ['Laptop', 'Smartphone'] 24 | 25 | # %% 3. Using Generators in Loops 26 | # Explanation: Iterate over a generator directly to save memory. 27 | # Example: 28 | quantities = [10, 20, 30, 40] 29 | stock_gen = (qty * 2 for qty in quantities) 30 | for doubled_qty in stock_gen: 31 | print(f"Doubled quantity: {doubled_qty}") 32 | # Output: Doubled quantity: 20, Doubled quantity: 40, Doubled quantity: 60, Doubled quantity: 80 33 | 34 | # %% Notes 35 | # Notes: 36 | # - Generators are memory-efficient for large datasets in ML (e.g., streaming data) or web apps (e.g., lazy API responses). 37 | # - Generators are single-use; convert to list if multiple iterations are needed. 38 | # - Use parentheses () for generator expressions, unlike [] for list comprehensions. -------------------------------------------------------------------------------- /Core Python Foundations/05 Exception Handling/01 Try-Except/Try-Except.py: -------------------------------------------------------------------------------- 1 | # %% Purpose 2 | # Python Exception Handling: Try-Except 3 | # Purpose: Try-Except blocks handle exceptions (errors) to prevent program crashes. 4 | # Key Features: Graceful error handling, improves robustness. 5 | 6 | # %% 1. Basic Try-Except 7 | # Explanation: Code in try block is executed; if an exception occurs, except block handles it. 8 | # Example: 9 | try: 10 | stock = int(input("Enter stock quantity: ")) # Simulating user input (e.g., "50") 11 | print(f"Stock recorded: {stock}") 12 | except ValueError: 13 | print("Error: Please enter a valid integer") 14 | # Output (if input is "50"): Stock recorded: 50 15 | # Output (if input is "abc"): Error: Please enter a valid integer 16 | 17 | # %% 2. Handling Specific Exceptions 18 | # Explanation: Catch specific exceptions to handle different error types. 19 | # Example: 20 | prices = [100, 200, "300", 400] 21 | try: 22 | total = sum(float(price) for price in prices) 23 | print(f"Total price: {total}") 24 | except ValueError: 25 | print("Error: Invalid price format in list") 26 | # Output: Error: Invalid price format in list 27 | 28 | # %% 3. Try-Except with Retail Scenario 29 | # Explanation: Handle errors in a retail context (e.g., processing product data). 30 | # Example: 31 | product = {"name": "Laptop", "price": "999.99"} # Simulating database input 32 | try: 33 | price = float(product["price"]) 34 | if price < 0: 35 | print("Warning: Negative price detected") 36 | else: 37 | print(f"Valid price: ${price:.2f}") 38 | except ValueError: 39 | print(f"Error: Invalid price for {product['name']}") 40 | # Output: Valid price: $999.99 41 | 42 | # %% Notes 43 | # Notes: 44 | # - Use try-except for operations prone to errors (e.g., user input, data parsing) in ML (data cleaning) or web apps (API handling). 45 | # - Catch specific exceptions to avoid masking unrelated errors. 46 | # - Avoid bare except clauses (e.g., except:) to prevent catching unintended exceptions. -------------------------------------------------------------------------------- /Core Python Foundations/05 Exception Handling/01 Try-Except/try_except_projects.py: -------------------------------------------------------------------------------- 1 | # Try-Except Projects 2 | # Purpose: Apply Try-Except exception handling through 5 projects. 3 | # Structure: Each project is separated by %% and includes description, tasks, and best solution. 4 | # Note: Solutions use retail-themed examples and simulate user inputs with fixed values for reproducibility. 5 | 6 | # %% Project 1: Price Input Validator 7 | # Difficulty: Basic 8 | # Description: Handle invalid user-entered price inputs. 9 | # Objective: Practice basic try-except for ValueError handling. 10 | # Tasks: 11 | # - Simulate user input for a product price. 12 | # - Use try-except to catch ValueError for invalid inputs. 13 | # - Print the valid price or an error message. 14 | # Expected Output: Error: Invalid price format 15 | simulated_input = "abc" # Simulating invalid input 16 | try: 17 | price = float(simulated_input) 18 | print(f"Valid price: ${price:.2f}") 19 | except ValueError: 20 | print("Error: Invalid price format") 21 | 22 | # %% Project 2: Stock List Summarizer 23 | # Difficulty: Basic 24 | # Description: Sum stock quantities from a list with potential invalid entries. 25 | # Objective: Use try-except to handle TypeError in list summation. 26 | # Tasks: 27 | # - Create a list of stock quantities with mixed types. 28 | # - Use try-except to catch TypeError when summing. 29 | # - Print the total or an error message. 30 | # Expected Output: Error: Invalid stock data type 31 | stock = [10, 20, "30", 40] 32 | try: 33 | total = sum(stock) 34 | print(f"Total stock: {total}") 35 | except TypeError: 36 | print("Error: Invalid stock data type") 37 | 38 | # %% Project 3: Product Data Accessor 39 | # Difficulty: Intermediate 40 | # Description: Access product stock from a dictionary with missing keys. 41 | # Objective: Practice try-except for KeyError handling. 42 | # Tasks: 43 | # - Create a product dictionary without a stock key. 44 | # - Use try-except to catch KeyError when accessing stock. 45 | # - Print the stock or an error message. 46 | # Expected Output: Error: Stock key not found for Smartphone 47 | product = {"name": "Smartphone", "price": 699.99} 48 | try: 49 | stock = product["stock"] 50 | print(f"Stock for {product['name']}: {stock}") 51 | except KeyError: 52 | print(f"Error: Stock key not found for {product['name']}") 53 | 54 | # %% Project 4: Order Price Parser 55 | # Difficulty: Intermediate 56 | # Description: Parse prices from an order list with potential invalid formats. 57 | # Objective: Use try-except to handle ValueError in a retail context. 58 | # Tasks: 59 | # - Create an order list with product names and prices (some invalid). 60 | # - Use try-except to convert prices to float and sum valid ones. 61 | # - Print the total or an error message. 62 | # Expected Output: Error: Invalid price format in order 63 | order = ["Laptop", "999.99", "Mouse", "abc"] 64 | try: 65 | total = sum(float(price) for price in order[1::2]) 66 | print(f"Order total: ${total:.2f}") 67 | except ValueError: 68 | print("Error: Invalid price format in order") 69 | 70 | # %% Project 5: Inventory Division Calculator 71 | # Difficulty: Advanced 72 | # Description: Calculate price per stock unit with multiple error possibilities. 73 | # Objective: Combine try-except for ValueError and ZeroDivisionError. 74 | # Tasks: 75 | # - Create a product dictionary with price and stock. 76 | # - Use try-except to handle ValueError (invalid price) and ZeroDivisionError (zero stock). 77 | # - Print the price per unit or an error message. 78 | # Expected Output: Error: Stock cannot be zero 79 | product = {"name": "Blender", "price": "39.99", "stock": 0} 80 | try: 81 | price = float(product["price"]) 82 | stock = int(product["stock"]) 83 | price_per_unit = price / stock 84 | print(f"Price per unit for {product['name']}: ${price_per_unit:.2f}") 85 | except ValueError: 86 | print("Error: Invalid price or stock format") 87 | except ZeroDivisionError: 88 | print("Error: Stock cannot be zero") -------------------------------------------------------------------------------- /Core Python Foundations/05 Exception Handling/02 Multiple Except Blocks/Multiple Except Blocks.py: -------------------------------------------------------------------------------- 1 | # %% Purpose 2 | # Python Exception Handling: Multiple Except Blocks 3 | # Purpose: Multiple except blocks handle different exception types for specific error handling. 4 | # Key Features: Targeted error management, improved debugging. 5 | 6 | # %% 1. Basic Multiple Except Blocks 7 | # Explanation: Define separate except blocks for each expected exception type. 8 | # Example: 9 | try: 10 | price = float(input("Enter price: ")) # Simulating input (e.g., "abc" or "-10") 11 | if price < 0: 12 | raise ValueError("Negative price not allowed") 13 | print(f"Price: ${price:.2f}") 14 | except ValueError: 15 | print("Invalid input or negative price") 16 | except TypeError: 17 | print("Type error occurred") 18 | # Output (if input is "abc"): Invalid input or negative price 19 | # Output (if input is "-10"): Invalid input or negative price 20 | 21 | # %% 2. Handling Multiple Exceptions 22 | # Explanation: Catch multiple exception types with specific actions. 23 | # Example: 24 | product = {"name": "Coffee Maker", "price": "49.99"} 25 | try: 26 | stock = product["stock"] # Missing key 27 | price = float(product["price"]) 28 | result = price / stock # Potential ZeroDivisionError 29 | print(f"Price per unit: ${result:.2f}") 30 | except KeyError: 31 | print("Error: Missing stock information") 32 | except ValueError: 33 | print("Error: Invalid price format") 34 | except ZeroDivisionError: 35 | print("Error: Stock cannot be zero") 36 | # Output: Error: Missing stock information 37 | 38 | # %% 3. Combining with Retail Logic 39 | # Explanation: Handle errors in a retail context with multiple exception types. 40 | # Example: 41 | order = ["Laptop", 2, "999.99"] 42 | try: 43 | product_name = order[0] 44 | quantity = int(order[1]) 45 | price = float(order[2]) 46 | total = quantity * price 47 | print(f"Order total for {product_name}: ${total:.2f}") 48 | except IndexError: 49 | print("Error: Incomplete order data") 50 | except ValueError: 51 | print("Error: Invalid quantity or price") 52 | except TypeError: 53 | print("Error: Invalid data type") 54 | # Output: Order total for Laptop: $1999.98 55 | 56 | # %% Notes 57 | # Notes: 58 | # - Order except blocks from specific to general (e.g., ValueError before Exception). 59 | # - Use in ML for robust data validation (e.g., handling missing features) or web apps for API error handling. 60 | # - Log exceptions for debugging in production systems. -------------------------------------------------------------------------------- /Core Python Foundations/05 Exception Handling/02 Multiple Except Blocks/multiple_except_projects.py: -------------------------------------------------------------------------------- 1 | # Multiple Except Blocks Projects 2 | # Purpose: Apply Multiple Except Blocks exception handling through 5 projects. 3 | # Structure: Each project is separated by %% and includes description, tasks, and best solution. 4 | # Note: Solutions use retail-themed examples and simulate user inputs with fixed values for reproducibility. 5 | 6 | # %% Project 1: Quantity Input Processor 7 | # Difficulty: Basic 8 | # Description: Process user-entered quantity with multiple error types. 9 | # Objective: Practice multiple except blocks for ValueError and TypeError. 10 | # Tasks: 11 | # - Simulate user input for a product quantity. 12 | # - Use try-except to catch ValueError and TypeError. 13 | # - Print the quantity or an appropriate error message. 14 | # Expected Output: Error: Invalid quantity format 15 | simulated_input = "abc" # Simulating invalid input 16 | try: 17 | quantity = int(simulated_input) 18 | print(f"Quantity: {quantity}") 19 | except ValueError: 20 | print("Error: Invalid quantity format") 21 | except TypeError: 22 | print("Error: Type mismatch") 23 | 24 | # %% Project 2: Product Stock Divider 25 | # Difficulty: Basic 26 | # Description: Divide price by stock with missing or zero stock. 27 | # Objective: Use multiple except blocks for KeyError and ZeroDivisionError. 28 | # Tasks: 29 | # - Create a product dictionary without stock. 30 | # - Use try-except to catch KeyError and ZeroDivisionError. 31 | # - Print the price per unit or an error message. 32 | # Expected Output: Error: Missing stock information 33 | product = {"name": "Coffee Maker", "price": "49.99"} 34 | try: 35 | stock = product["stock"] 36 | price = float(product["price"]) 37 | price_per_unit = price / stock 38 | print(f"Price per unit: ${price_per_unit:.2f}") 39 | except KeyError: 40 | print("Error: Missing stock information") 41 | except ZeroDivisionError: 42 | print("Error: Stock cannot be zero") 43 | 44 | # %% Project 3: Order Data Validator 45 | # Difficulty: Intermediate 46 | # Description: Validate an order list with multiple potential errors. 47 | # Objective: Handle IndexError, ValueError, and TypeError in a retail context. 48 | # Tasks: 49 | # - Create an incomplete order list. 50 | # - Use try-except to catch IndexError, ValueError, and TypeError. 51 | # - Print the order total or an error message. 52 | # Expected Output: Error: Incomplete order data 53 | order = ["Smartphone", "2"] 54 | try: 55 | name = order[0] 56 | quantity = int(order[1]) 57 | price = float(order[2]) 58 | total = quantity * price 59 | print(f"Order total for {name}: ${total:.2f}") 60 | except IndexError: 61 | print("Error: Incomplete order data") 62 | except ValueError: 63 | print("Error: Invalid quantity or price") 64 | except TypeError: 65 | print("Error: Invalid data type") 66 | 67 | # %% Project 4: Price List Processor 68 | # Difficulty: Intermediate 69 | # Description: Process a list of prices with mixed types and invalid formats. 70 | # Objective: Use multiple except blocks for ValueError and TypeError. 71 | # Tasks: 72 | # - Create a list of prices with invalid entries. 73 | # - Use try-except to catch ValueError and TypeError while summing prices. 74 | # - Print the total or an error message. 75 | # Expected Output: Error: Invalid price format 76 | prices = [100, "200", None, 400] 77 | try: 78 | total = sum(float(price) for price in prices) 79 | print(f"Total price: ${total:.2f}") 80 | except ValueError: 81 | print("Error: Invalid price format") 82 | except TypeError: 83 | print("Error: Invalid price type") 84 | 85 | # %% Project 5: Inventory Analysis 86 | # Difficulty: Advanced 87 | # Description: Analyze inventory data with multiple error scenarios. 88 | # Objective: Combine multiple except blocks for ValueError, KeyError, and ZeroDivisionError. 89 | # Tasks: 90 | # - Create a product dictionary with potential invalid data. 91 | # - Use try-except to handle ValueError, KeyError, and ZeroDivisionError. 92 | # - Print the price per stock unit or an error message. 93 | # Expected Output: Error: Invalid price format 94 | product = {"name": "Tablet", "price": "abc"} 95 | try: 96 | price = float(product["price"]) 97 | stock = product["stock"] 98 | price_per_unit = price / stock 99 | print(f"Price per unit for {product['name']}: ${price_per_unit:.2f}") 100 | except ValueError: 101 | print("Error: Invalid price format") 102 | except KeyError: 103 | print("Error: Missing stock information") 104 | except ZeroDivisionError: 105 | print("Error: Stock cannot be zero") -------------------------------------------------------------------------------- /Core Python Foundations/05 Exception Handling/03 Else Clause/Else Clause.py: -------------------------------------------------------------------------------- 1 | # %% Purpose 2 | # Python Exception Handling: Else Clause 3 | # Purpose: Else clause in try-except runs if no exception occurs in the try block. 4 | # Key Features: Separates success logic from error handling. 5 | 6 | # %% 1. Basic Try-Except-Else 7 | # Explanation: Execute else block only if try block succeeds. 8 | # Example: 9 | try: 10 | price = float(input("Enter price: ")) # Simulating input (e.g., "49.99") 11 | except ValueError: 12 | print("Error: Invalid price format") 13 | else: 14 | print(f"Valid price: ${price:.2f}") 15 | # Output (if input is "49.99"): Valid price: $49.99 16 | # Output (if input is "abc"): Error: Invalid price format 17 | 18 | # %% 2. Else with Multiple Exceptions 19 | # Explanation: Combine with multiple except blocks for robust handling. 20 | # Example: 21 | product = {"name": "Laptop", "price": "999.99"} 22 | try: 23 | price = float(product["price"]) 24 | stock = product["stock"] 25 | except ValueError: 26 | print("Error: Invalid price format") 27 | except KeyError: 28 | print("Error: Missing stock information") 29 | else: 30 | print(f"Product {product['name']}: Price ${price:.2f}, Stock {stock}") 31 | # Output: Error: Missing stock information 32 | 33 | # %% 3. Retail Scenario with Else 34 | # Explanation: Use else to process valid data in a retail context. 35 | # Example: 36 | order = ["Smartphone", "2", "699.99"] 37 | try: 38 | quantity = int(order[1]) 39 | price = float(order[2]) 40 | except ValueError: 41 | print("Error: Invalid quantity or price") 42 | except IndexError: 43 | print("Error: Incomplete order data") 44 | else: 45 | total = quantity * price 46 | print(f"Order for {order[0]}: Total ${total:.2f}") 47 | # Output: Order for Smartphone: Total $1399.98 48 | 49 | # %% Notes 50 | # Notes: 51 | # - Else clause keeps success logic separate, improving code clarity. 52 | # - Use in ML for data validation (e.g., ensuring clean features) or web apps for user input processing. 53 | # - Else runs only if no exception is raised in try block. -------------------------------------------------------------------------------- /Core Python Foundations/05 Exception Handling/03 Else Clause/else_clause_projects.py: -------------------------------------------------------------------------------- 1 | # Else Clause Projects 2 | # Purpose: Apply Else Clause in try-except through 5 projects. 3 | # Structure: Each project is separated by %% and includes description, tasks, and best solution. 4 | # Note: Solutions use retail-themed examples and simulate user inputs with fixed values for reproducibility. 5 | 6 | # %% Project 1: Stock Input Validator 7 | # Difficulty: Basic 8 | # Description: Validate user-entered stock quantity with success confirmation. 9 | # Objective: Practice try-except-else for ValueError handling. 10 | # Tasks: 11 | # - Simulate user input for stock quantity. 12 | # - Use try-except-else to catch ValueError and confirm valid input in else. 13 | # - Print the stock or an error message. 14 | # Expected Output: Valid stock: 50 15 | simulated_input = "50" # Simulating valid input 16 | try: 17 | stock = int(simulated_input) 18 | except ValueError: 19 | print("Error: Invalid stock format") 20 | else: 21 | print(f"Valid stock: {stock}") 22 | 23 | # %% Project 2: Product Value Calculator 24 | # Difficulty: Basic 25 | # Description: Calculate total value of a product with valid data. 26 | # Objective: Use try-except-else to handle KeyError and ValueError. 27 | # Tasks: 28 | # - Create a product dictionary with price and stock. 29 | # - Use try-except-else to validate data and calculate total in else. 30 | # - Print the total or an error message. 31 | # Expected Output: Total value: $1999.98 32 | product = {"name": "Laptop", "price": "999.99", "stock": "2"} 33 | try: 34 | price = float(product["price"]) 35 | stock = int(product["stock"]) 36 | except (ValueError, KeyError): 37 | print("Error: Invalid or missing data") 38 | else: 39 | total = price * stock 40 | print(f"Total value: ${total:.2f}") 41 | 42 | # %% Project 3: Order Processor 43 | # Difficulty: Intermediate 44 | # Description: Process an order list and confirm valid data. 45 | # Objective: Use try-except-else for IndexError and ValueError in a retail context. 46 | # Tasks: 47 | # - Create an order list with name, quantity, and price. 48 | # - Use try-except-else to validate and process total in else. 49 | # - Print the total or an error message. 50 | # Expected Output: Order total for Mouse: $149.95 51 | order = ["Mouse", "5", "29.99"] 52 | try: 53 | quantity = int(order[1]) 54 | price = float(order[2]) 55 | except ValueError: 56 | print("Error: Invalid quantity or price") 57 | except IndexError: 58 | print("Error: Incomplete order data") 59 | else: 60 | total = quantity * price 61 | print(f"Order total for {order[0]}: ${total:.2f}") 62 | 63 | # %% Project 4: Price Parser 64 | # Difficulty: Intermediate 65 | # Description: Parse and sum prices from a list with success confirmation. 66 | # Objective: Use try-except-else to handle ValueError and TypeError. 67 | # Tasks: 68 | # - Create a list of prices with potential invalid entries. 69 | # - Use try-except-else to sum valid prices in else. 70 | # - Print the total or an error message. 71 | # Expected Output: Error: Invalid price format 72 | prices = [100, "abc", 300] 73 | try: 74 | total = sum(float(price) for price in prices) 75 | except (ValueError, TypeError): 76 | print("Error: Invalid price format") 77 | else: 78 | print(f"Total price: ${total:.2f}") 79 | 80 | # %% Project 5: Inventory Checker 81 | # Difficulty: Advanced 82 | # Description: Check inventory data and confirm valid calculations. 83 | # Objective: Combine try-except-else for multiple exceptions in a retail context. 84 | # Tasks: 85 | # - Create a product dictionary with price, stock, and name. 86 | # - Use try-except-else to handle ValueError, KeyError, and ZeroDivisionError, calculating price per unit in else. 87 | # - Print the result or an error message. 88 | # Expected Output: Error: Missing stock information 89 | product = {"name": "Tablet", "price": "499.99"} 90 | try: 91 | price = float(product["price"]) 92 | stock = int(product["stock"]) 93 | price_per_unit = price / stock 94 | except ValueError: 95 | print("Error: Invalid price or stock format") 96 | except KeyError: 97 | print("Error: Missing stock information") 98 | except ZeroDivisionError: 99 | print("Error: Stock cannot be zero") 100 | else: 101 | print(f"Price per unit for {product['name']}: ${price_per_unit:.2f}") -------------------------------------------------------------------------------- /Core Python Foundations/05 Exception Handling/04 Finally Clause/Finally Clause.py: -------------------------------------------------------------------------------- 1 | # %% Purpose 2 | # Python Exception Handling: Finally Clause 3 | # Purpose: Finally clause runs regardless of whether an exception occurs, useful for cleanup. 4 | # Key Features: Ensures execution of critical code (e.g., closing resources). 5 | 6 | # %% 1. Basic Try-Except-Finally 7 | # Explanation: Finally block executes after try and except, even if an exception occurs. 8 | # Example: 9 | try: 10 | price = float(input("Enter price: ")) # Simulating input (e.g., "49.99" or "abc") 11 | print(f"Price: ${price:.2f}") 12 | except ValueError: 13 | print("Error: Invalid price format") 14 | finally: 15 | print("Processing complete") 16 | # Output (if input is "49.99"): Price: $49.99, Processing complete 17 | # Output (if input is "abc"): Error: Invalid price format, Processing complete 18 | 19 | # %% 2. Finally with Multiple Exceptions 20 | # Explanation: Use finally with multiple except blocks for consistent cleanup. 21 | # Example: 22 | product = {"name": "Smartphone", "price": "699.99"} 23 | try: 24 | price = float(product["price"]) 25 | stock = product["stock"] 26 | except ValueError: 27 | print("Error: Invalid price format") 28 | except KeyError: 29 | print("Error: Missing stock information") 30 | finally: 31 | print("Product processing finished") 32 | # Output: Error: Missing stock information, Product processing finished 33 | 34 | # %% 3. Retail Scenario with Finally 35 | # Explanation: Use finally to log or clean up in a retail context. 36 | # Example: 37 | order = ["Laptop", "2", "999.99"] 38 | try: 39 | quantity = int(order[1]) 40 | price = float(order[2]) 41 | total = quantity * price 42 | print(f"Order total: ${total:.2f}") 43 | except (ValueError, IndexError): 44 | print("Error: Invalid or incomplete order") 45 | finally: 46 | print("Order processing logged") 47 | # Output: Order total: $1999.98, Order processing logged 48 | 49 | # %% Notes 50 | # Notes: 51 | # - Finally is ideal for cleanup (e.g., closing files, releasing database connections) in ML or web apps. 52 | # - Runs even if return or break statements are used in try/except. 53 | # - Use for logging or resource management in production code. -------------------------------------------------------------------------------- /Core Python Foundations/05 Exception Handling/04 Finally Clause/finally_clause_projects.py: -------------------------------------------------------------------------------- 1 | # Finally Clause Projects 2 | # Purpose: Apply Finally Clause in try-except through 5 projects. 3 | # Structure: Each project is separated by %% and includes description, tasks, and best solution. 4 | # Note: Solutions use retail-themed examples and simulate user inputs with fixed values for reproducibility. 5 | 6 | # %% Project 1: Price Input Logger 7 | # Difficulty: Basic 8 | # Description: Process user-entered price with logging. 9 | # Objective: Practice try-except-finally for ValueError handling with cleanup. 10 | # Tasks: 11 | # - Simulate user input for a price. 12 | # - Use try-except-finally to catch ValueError and log completion. 13 | # - Print the price, error, and log message. 14 | # Expected Output: Error: Invalid price format, Price processing logged 15 | simulated_input = "abc" # Simulating invalid input 16 | try: 17 | price = float(simulated_input) 18 | print(f"Price: ${price:.2f}") 19 | except ValueError: 20 | print("Error: Invalid price format") 21 | finally: 22 | print("Price processing logged") 23 | 24 | # %% Project 2: Product Data Logger 25 | # Difficulty: Basic 26 | # Description: Access product data with logging regardless of errors. 27 | # Objective: Use try-except-finally for KeyError handling. 28 | # Tasks: 29 | # - Create a product dictionary without stock. 30 | # - Use try-except-finally to catch KeyError and log processing. 31 | # - Print the stock, error, and log message. 32 | # Expected Output: Error: Missing stock information, Product processing logged 33 | product = {"name": "Smartphone", "price": "699.99"} 34 | try: 35 | stock = product["stock"] 36 | print(f"Stock for {product['name']}: {stock}") 37 | except KeyError: 38 | print("Error: Missing stock information") 39 | finally: 40 | print("Product processing logged") 41 | 42 | # %% Project 3: Order Processor Logger 43 | # Difficulty: Intermediate 44 | # Description: Process an order list with logging for all outcomes. 45 | # Objective: Use try-except-finally for ValueError and IndexError in a retail context. 46 | # Tasks: 47 | # - Create an order list with name, quantity, and price. 48 | # - Use try-except-finally to process total and log completion. 49 | # - Print the total, error, and log message. 50 | # Expected Output: Order total for Mouse: $149.95, Order processing logged 51 | order = ["Mouse", "5", "29.99"] 52 | try: 53 | quantity = int(order[1]) 54 | price = float(order[2]) 55 | total = quantity * price 56 | print(f"Order total for {order[0]}: ${total:.2f}") 57 | except (ValueError, IndexError): 58 | print("Error: Invalid or incomplete order") 59 | finally: 60 | print("Order processing logged") 61 | 62 | # %% Project 4: Stock Validator Logger 63 | # Difficulty: Intermediate 64 | # Description: Validate stock quantities with logging. 65 | # Objective: Use try-except-finally for ValueError and TypeError. 66 | # Tasks: 67 | # - Create a list of stock quantities with invalid entries. 68 | # - Use try-except-finally to sum quantities and log processing. 69 | # - Print the total, error, and log message. 70 | # Expected Output: Error: Invalid stock format, Stock processing logged 71 | stock = [10, "20", 30] 72 | try: 73 | total = sum(int(qty) for qty in stock) 74 | print(f"Total stock: {total}") 75 | except (ValueError, TypeError): 76 | print("Error: Invalid stock format") 77 | finally: 78 | print("Stock processing logged") 79 | 80 | # %% Project 5: Inventory Analysis Logger 81 | # Difficulty: Advanced 82 | # Description: Analyze inventory with logging for all scenarios. 83 | # Objective: Combine try-except-finally for multiple exceptions. 84 | # Tasks: 85 | # - Create a product dictionary with potential invalid data. 86 | # - Use try-except-finally to handle ValueError, KeyError, and ZeroDivisionError, logging completion. 87 | # - Print the price per unit, error, and log message. 88 | # Expected Output: Error: Stock cannot be zero, Inventory processing logged 89 | product = {"name": "Blender", "price": "39.99", "stock": "0"} 90 | try: 91 | price = float(product["price"]) 92 | stock = int(product["stock"]) 93 | price_per_unit = price / stock 94 | print(f"Price per unit for {product['name']}: ${price_per_unit:.2f}") 95 | except ValueError: 96 | print("Error: Invalid price or stock format") 97 | except KeyError: 98 | print("Error: Missing stock information") 99 | except ZeroDivisionError: 100 | print("Error: Stock cannot be zero") 101 | finally: 102 | print("Inventory processing logged") -------------------------------------------------------------------------------- /Core Python Foundations/05 Exception Handling/05 Raise Statement/Raise Statement.py: -------------------------------------------------------------------------------- 1 | # %% Purpose 2 | # Python Exception Handling: Raise Statement 3 | # Purpose: Raise statement triggers an exception explicitly to enforce conditions. 4 | # Key Features: Custom error handling, program control. 5 | 6 | # %% 1. Basic Raise 7 | # Explanation: Raise an exception with raise ExceptionType("message"). 8 | # Example: 9 | price = -50 10 | if price < 0: 11 | raise ValueError("Price cannot be negative") 12 | # Output: ValueError: Price cannot be negative (program stops unless caught) 13 | 14 | # %% 2. Raise with Try-Except 15 | # Explanation: Raise an exception and handle it in a try-except block. 16 | # Example: 17 | try: 18 | stock = 0 19 | if stock <= 0: 20 | raise ValueError("Stock must be positive") 21 | print(f"Stock: {stock}") 22 | except ValueError as e: 23 | print(f"Error: {e}") 24 | # Output: Error: Stock must be positive 25 | 26 | # %% 3. Retail Scenario with Raise 27 | # Explanation: Enforce business rules in a retail context. 28 | # Example: 29 | order = {"name": "Laptop", "quantity": 2, "price": 999.99} 30 | try: 31 | if order["quantity"] > 100: 32 | raise ValueError("Quantity exceeds maximum limit") 33 | if order["price"] < 0: 34 | raise ValueError("Negative price not allowed") 35 | total = order["quantity"] * order["price"] 36 | print(f"Order total for {order['name']}: ${total:.2f}") 37 | except ValueError as e: 38 | print(f"Order error: {e}") 39 | # Output: Order total for Laptop: $1999.98 40 | 41 | # %% Notes 42 | # Notes: 43 | # - Use raise to enforce business rules in ML (e.g., invalid model parameters) or web apps (e.g., API validation). 44 | # - Combine with try-except to handle raised exceptions gracefully. 45 | # - Include descriptive error messages for debugging. -------------------------------------------------------------------------------- /Core Python Foundations/05 Exception Handling/05 Raise Statement/raise_statement_projects.py: -------------------------------------------------------------------------------- 1 | # Raise Statement Projects 2 | # Purpose: Apply Raise Statement exception handling through 5 projects. 3 | # Structure: Each project is separated by %% and includes description, tasks, and best solution. 4 | # Note: Solutions use retail-themed examples and simulate user inputs with fixed values for reproducibility. 5 | 6 | # %% Project 1: Negative Price Enforcer 7 | # Difficulty: Basic 8 | # Description: Enforce non-negative prices with explicit error raising. 9 | # Objective: Practice raising ValueError for invalid conditions. 10 | # Tasks: 11 | # - Simulate a product price. 12 | # - Use try-except to raise and catch ValueError if price is negative. 13 | # - Print the price or error message. 14 | # Expected Output: Error: Negative price not allowed 15 | price = -50 16 | try: 17 | if price < 0: 18 | raise ValueError("Negative price not allowed") 19 | print(f"Price: ${price:.2f}") 20 | except ValueError as e: 21 | print(f"Error: {e}") 22 | 23 | # %% Project 2: Zero Stock Enforcer 24 | # Difficulty: Basic 25 | # Description: Enforce positive stock quantities in a product dictionary. 26 | # Objective: Use raise with try-except for ValueError handling. 27 | # Tasks: 28 | # - Create a product dictionary with zero stock. 29 | # - Use try-except to raise and catch ValueError if stock is zero. 30 | # - Print the stock or error message. 31 | # Expected Output: Error: Zero stock not allowed 32 | product = {"name": "Blender", "stock": 0} 33 | try: 34 | if product["stock"] == 0: 35 | raise ValueError("Zero stock not allowed") 36 | print(f"Stock for {product['name']}: {product['stock']}") 37 | except ValueError as e: 38 | print(f"Error: {e}") 39 | 40 | # %% Project 3: Order Quantity Limiter 41 | # Difficulty: Intermediate 42 | # Description: Limit order quantities to a maximum value. 43 | # Objective: Raise ValueError for excessive quantities in a retail context. 44 | # Tasks: 45 | # - Create an order dictionary with name, quantity, and price. 46 | # - Use try-except to raise and catch ValueError if quantity > 100. 47 | # - Print the order total or error message. 48 | # Expected Output: Order total for Smartphone: $1399.98 49 | order = {"name": "Smartphone", "quantity": 2, "price": 699.99} 50 | try: 51 | if order["quantity"] > 100: 52 | raise ValueError("Quantity exceeds maximum limit") 53 | total = order["quantity"] * order["price"] 54 | print(f"Order total for {order['name']}: ${total:.2f}") 55 | except ValueError as e: 56 | print(f"Error: {e}") 57 | 58 | # %% Project 4: Price Type Validator 59 | # Difficulty: Intermediate 60 | # Description: Enforce numeric price types in a product list. 61 | # Objective: Raise TypeError for non-numeric prices. 62 | # Tasks: 63 | # - Create a list of products with mixed price types. 64 | # - Use try-except to raise and catch TypeError for non-numeric prices. 65 | # - Print valid prices or error message. 66 | # Expected Output: Error: Price must be numeric 67 | products = [{"name": "Mouse", "price": "abc"}] 68 | try: 69 | for p in products: 70 | if not isinstance(p["price"], (int, float)): 71 | raise TypeError("Price must be numeric") 72 | print(f"Price for {p['name']}: ${p['price']:.2f}") 73 | except TypeError as e: 74 | print(f"Error: {e}") 75 | 76 | # %% Project 5: Complex Order Validator 77 | # Difficulty: Advanced 78 | # Description: Validate order data with multiple business rules. 79 | # Objective: Combine raise for ValueError and TypeError in a retail context. 80 | # Tasks: 81 | # - Create an order dictionary with potential invalid data. 82 | # - Use try-except to raise and catch ValueError (negative price) and TypeError (non-integer quantity). 83 | # - Print the order total or error message. 84 | # Expected Output: Error: Quantity must be an integer 85 | order = {"name": "Tablet", "quantity": "5", "price": 499.99} 86 | try: 87 | if not isinstance(order["quantity"], int): 88 | raise TypeError("Quantity must be an integer") 89 | if order["price"] < 0: 90 | raise ValueError("Negative price not allowed") 91 | total = order["quantity"] * order["price"] 92 | print(f"Order total for {order['name']}: ${total:.2f}") 93 | except (ValueError, TypeError) as e: 94 | print(f"Error: {e}") -------------------------------------------------------------------------------- /Core Python Foundations/05 Exception Handling/06 Custom Exceptions/Custom Exceptions.py: -------------------------------------------------------------------------------- 1 | # %% Purpose 2 | # Python Exception Handling: Custom Exceptions 3 | # Purpose: Custom exceptions allow user-defined error types for specific scenarios. 4 | # Key Features: Extends built-in exceptions, enhances code modularity. 5 | 6 | # %% 1. Defining a Custom Exception 7 | # Explanation: Create a class inheriting from Exception or its subclasses. 8 | # Example: 9 | class InvalidStockError(Exception): 10 | pass 11 | 12 | try: 13 | stock = -10 14 | if stock < 0: 15 | raise InvalidStockError("Stock cannot be negative") 16 | except InvalidStockError as e: 17 | print(f"Error: {e}") 18 | # Output: Error: Stock cannot be negative 19 | 20 | # %% 2. Custom Exception with Attributes 21 | # Explanation: Add attributes to custom exceptions for detailed error info. 22 | # Example: 23 | class PriceError(Exception): 24 | def __init__(self, message, price): 25 | super().__init__(message) 26 | self.price = price 27 | 28 | try: 29 | price = -50 30 | if price < 0: 31 | raise PriceError("Price must be non-negative", price) 32 | except PriceError as e: 33 | print(f"Error: {e}, Invalid price: {e.price}") 34 | # Output: Error: Price must be non-negative, Invalid price: -50 35 | 36 | # %% 3. Retail Scenario with Custom Exception 37 | # Explanation: Use custom exceptions for retail business rules. 38 | # Example: 39 | class OrderError(Exception): 40 | def __init__(self, message, order_details): 41 | super().__init__(message) 42 | self.order_details = order_details 43 | 44 | order = {"name": "Smartphone", "quantity": 200, "price": 699.99} 45 | try: 46 | if order["quantity"] > 100: 47 | raise OrderError("Quantity exceeds maximum limit", order) 48 | total = order["quantity"] * order["price"] 49 | print(f"Order total for {order['name']}: ${total:.2f}") 50 | except OrderError as e: 51 | print(f"Order error: {e}, Details: {e.order_details}") 52 | # Output: Order error: Quantity exceeds maximum limit, Details: {'name': 'Smartphone', 'quantity': 200, 'price': 699.99} 53 | 54 | # %% Notes 55 | # Notes: 56 | # - Custom exceptions improve code readability and maintainability in ML (e.g., model validation) or web apps (e.g., API error responses). 57 | # - Inherit from Exception or specific subclasses (e.g., ValueError) for appropriate context. 58 | # - Include attributes for detailed error reporting. -------------------------------------------------------------------------------- /Core Python Foundations/05 Exception Handling/06 Custom Exceptions/custom_exceptions_projects.py: -------------------------------------------------------------------------------- 1 | # Custom Exceptions Projects 2 | # Purpose: Apply Custom Exceptions through 5 projects. 3 | # Structure: Each project is separated by %% and includes description, tasks, and best solution. 4 | # Note: Solutions use retail-themed examples and simulate user inputs with fixed values for reproducibility. 5 | 6 | # %% Project 1: Low Stock Exception 7 | # Difficulty: Basic 8 | # Description: Define and raise a custom exception for low stock levels. 9 | # Objective: Practice defining and using a basic custom exception. 10 | # Tasks: 11 | # - Define a custom LowStockError. 12 | # - Raise it if stock is below 10. 13 | # - Print the stock or error message. 14 | # Expected Output: Error: Stock too low 15 | class LowStockError(Exception): 16 | pass 17 | 18 | stock = 5 19 | try: 20 | if stock < 10: 21 | raise LowStockError("Stock too low") 22 | print(f"Stock: {stock}") 23 | except LowStockError as e: 24 | print(f"Error: {e}") 25 | 26 | # %% Project 2: Negative Price Exception 27 | # Difficulty: Basic 28 | # Description: Create a custom exception with a price attribute for negative prices. 29 | # Objective: Use custom exception with attributes for detailed error reporting. 30 | # Tasks: 31 | # - Define a NegativePriceError with a price attribute. 32 | # - Raise it if price is negative. 33 | # - Print the error and price value. 34 | # Expected Output: Error: Negative price not allowed, Price: -20 35 | class NegativePriceError(Exception): 36 | def __init__(self, message, price): 37 | super().__init__(message) 38 | self.price = price 39 | 40 | price = -20 41 | try: 42 | if price < 0: 43 | raise NegativePriceError("Negative price not allowed", price) 44 | print(f"Price: ${price:.2f}") 45 | except NegativePriceError as e: 46 | print(f"Error: {e}, Price: {e.price}") 47 | 48 | # %% Project 3: Invalid Order Exception 49 | # Difficulty: Intermediate 50 | # Description: Define a custom exception for invalid order quantities. 51 | # Objective: Use custom exception in a retail context with order details. 52 | # Tasks: 53 | # - Define an InvalidOrderError with order details. 54 | # - Raise it if quantity is zero. 55 | # - Print the error and order details. 56 | # Expected Output: Error: Quantity cannot be zero, Order: {'name': 'Mouse', 'quantity': 0, 'price': 29.99} 57 | class InvalidOrderError(Exception): 58 | def __init__(self, message, order): 59 | super().__init__(message) 60 | self.order = order 61 | 62 | order = {"name": "Mouse", "quantity": 0, "price": 29.99} 63 | try: 64 | if order["quantity"] == 0: 65 | raise InvalidOrderError("Quantity cannot be zero", order) 66 | total = order["quantity"] * order["price"] 67 | print(f"Order total for {order['name']}: ${total:.2f}") 68 | except InvalidOrderError as e: 69 | print(f"Error: {e}, Order: {e.order}") 70 | 71 | # %% Project 4: Stock Format Exception 72 | # Difficulty: Intermediate 73 | # Description: Create a custom exception for invalid stock formats in a list. 74 | # Objective: Combine custom exception with try-except for TypeError handling. 75 | # Tasks: 76 | # - Define a StockFormatError. 77 | # - Raise it for non-numeric stock entries in a list. 78 | # - Print the error message. 79 | # Expected Output: Error: Invalid stock format 80 | class StockFormatError(Exception): 81 | pass 82 | 83 | stock = [10, "20", 30] 84 | try: 85 | for qty in stock: 86 | if not isinstance(qty, (int, float)): 87 | raise StockFormatError("Invalid stock format") 88 | total = sum(stock) 89 | print(f"Total stock: {total}") 90 | except StockFormatError as e: 91 | print(f"Error: {e}") 92 | 93 | # %% Project 5: Complex Order Validator 94 | # Difficulty: Advanced 95 | # Description: Validate orders with multiple custom exceptions. 96 | # Objective: Use multiple custom exceptions for comprehensive validation. 97 | # Tasks: 98 | # - Define NegativePriceError and InvalidOrderError. 99 | # - Raise them for negative prices or excessive quantities. 100 | # - Print the error and relevant details. 101 | # Expected Output: Error: Quantity exceeds maximum limit, Order: {'name': 'Laptop', 'quantity': 200, 'price': 999.99} 102 | class NegativePriceError(Exception): 103 | def __init__(self, message, price): 104 | super().__init__(message) 105 | self.price = price 106 | 107 | class InvalidOrderError(Exception): 108 | def __init__(self, message, order): 109 | super().__init__(message) 110 | self.order = order 111 | 112 | order = {"name": "Laptop", "quantity": 200, "price": 999.99} 113 | try: 114 | if order["price"] < 0: 115 | raise NegativePriceError("Negative price not allowed", order["price"]) 116 | if order["quantity"] > 100: 117 | raise InvalidOrderError("Quantity exceeds maximum limit", order) 118 | total = order["quantity"] * order["price"] 119 | print(f"Order total for {order['name']}: ${total:.2f}") 120 | except NegativePriceError as e: 121 | print(f"Error: {e}, Price: {e.price}") 122 | except InvalidOrderError as e: 123 | print(f"Error: {e}, Order: {e.order}") -------------------------------------------------------------------------------- /Core Python Foundations/06 Object-Oriented Programming/01 Classes and Objects/Classes and Objects.py: -------------------------------------------------------------------------------- 1 | # %% Purpose 2 | # Python Object-Oriented Programming: Classes and Objects 3 | # Purpose: Classes define blueprints for objects, which are instances of classes. 4 | # Key Features: Encapsulates data and behavior, foundation of OOP. 5 | 6 | # %% 1. Defining a Class and Creating an Object 7 | # Explanation: Use 'class' keyword to define a class; instantiate with class name. 8 | # Example: 9 | class Product: 10 | pass 11 | 12 | # Create objects 13 | laptop = Product() 14 | smartphone = Product() 15 | print("Objects created:", laptop, smartphone) 16 | # Output: Objects created: <__main__.Product object at ...> <__main__.Product object at ...> 17 | 18 | # %% 2. Initializing Objects with __init__ 19 | # Explanation: __init__ method initializes object attributes. 20 | # Example: 21 | class Product: 22 | def __init__(self, name, price): 23 | self.name = name 24 | self.price = price 25 | 26 | laptop = Product("Laptop Pro", 999.99) 27 | print(f"Product: {laptop.name}, Price: ${laptop.price:.2f}") 28 | # Output: Product: Laptop Pro, Price: $999.99 29 | 30 | # %% 3. Retail Scenario with Classes 31 | # Explanation: Model a retail product with attributes. 32 | # Example: 33 | class Product: 34 | def __init__(self, name, price, stock): 35 | self.name = name 36 | self.price = price 37 | self.stock = stock 38 | 39 | coffee_maker = Product("Coffee Maker", 49.99, 30) 40 | print(f"Product: {coffee_maker.name}, Price: ${coffee_maker.price:.2f}, Stock: {coffee_maker.stock}") 41 | # Output: Product: Coffee Maker, Price: $49.99, Stock: 30 42 | 43 | # %% Notes 44 | # Notes: 45 | # - Classes are templates; objects are instances with specific data. 46 | # - Use in ML for modeling entities (e.g., datasets) or web apps for data structures (e.g., user models). 47 | # - __init__ is a constructor, called automatically when an object is created. -------------------------------------------------------------------------------- /Core Python Foundations/06 Object-Oriented Programming/02 Attributes/Attributes.py: -------------------------------------------------------------------------------- 1 | # %% Purpose 2 | # Python Object-Oriented Programming: Attributes 3 | # Purpose: Attributes are variables that belong to a class or object, storing data. 4 | # Key Features: Instance attributes (per object), class attributes (shared). 5 | 6 | # %% 1. Instance Attributes 7 | # Explanation: Defined in __init__, unique to each object. 8 | # Example: 9 | class Product: 10 | def __init__(self, name, price): 11 | self.name = name # Instance attribute 12 | self.price = price # Instance attribute 13 | 14 | laptop = Product("Laptop Pro", 999.99) 15 | smartphone = Product("Smartphone X", 699.99) 16 | print(f"Laptop: {laptop.name}, ${laptop.price:.2f}") 17 | print(f"Smartphone: {smartphone.name}, ${smartphone.price:.2f}") 18 | # Output: Laptop: Laptop Pro, $999.99 19 | # Smartphone: Smartphone X, $699.99 20 | 21 | # %% 2. Class Attributes 22 | # Explanation: Defined outside __init__, shared across all objects. 23 | # Example: 24 | class Product: 25 | store_name = "Tech Retail" # Class attribute 26 | def __init__(self, name, price): 27 | self.name = name 28 | self.price = price 29 | 30 | laptop = Product("Laptop", 999.99) 31 | print(f"Store: {Product.store_name}, Product: {laptop.name}") 32 | print(f"Store from object: {laptop.store_name}") 33 | # Output: Store: Tech Retail, Product: Laptop 34 | # Store from object: Tech Retail 35 | 36 | # %% 3. Modifying Attributes 37 | # Explanation: Update instance or class attributes dynamically. 38 | # Example: 39 | class Product: 40 | tax_rate = 0.1 # Class attribute 41 | def __init__(self, name, price): 42 | self.name = name 43 | self.price = price 44 | 45 | blender = Product("Blender", 39.99) 46 | blender.price = 35.99 # Update instance attribute 47 | Product.tax_rate = 0.15 # Update class attribute 48 | print(f"Updated price: ${blender.price:.2f}, New tax rate: {Product.tax_rate}") 49 | # Output: Updated price: $35.99, New tax rate: 0.15 50 | 51 | # %% Notes 52 | # Notes: 53 | # - Instance attributes are unique; class attributes are shared. 54 | # - Use in ML for model parameters (e.g., weights) or web apps for shared configs (e.g., API keys). 55 | # - Access attributes via dot notation (object.attribute). -------------------------------------------------------------------------------- /Core Python Foundations/06 Object-Oriented Programming/03 Methods/Methods.py: -------------------------------------------------------------------------------- 1 | # %% Purpose 2 | # Python Object-Oriented Programming: Methods 3 | # Purpose: Methods are functions defined in a class that operate on objects. 4 | # Key Features: Encapsulate behavior, access instance/class data. 5 | 6 | # %% 1. Instance Methods 7 | # Explanation: Methods that take 'self' as first parameter, access instance attributes. 8 | # Example: 9 | class Product: 10 | def __init__(self, name, price): 11 | self.name = name 12 | self.price = price 13 | def apply_discount(self, discount): 14 | self.price *= (1 - discount) 15 | return self.price 16 | 17 | laptop = Product("Laptop Pro", 999.99) 18 | new_price = laptop.apply_discount(0.1) 19 | print(f"Discounted price: ${new_price:.2f}") 20 | # Output: Discounted price: $899.99 21 | 22 | # %% 2. Calling Methods 23 | # Explanation: Methods are called on objects using dot notation. 24 | # Example: 25 | class Product: 26 | def __init__(self, name, price, stock): 27 | self.name = name 28 | self.price = price 29 | self.stock = stock 30 | def check_stock(self): 31 | return f"{self.name}: {self.stock} in stock" 32 | 33 | coffee_maker = Product("Coffee Maker", 49.99, 30) 34 | print(coffee_maker.check_stock()) 35 | # Output: Coffee Maker: 30 in stock 36 | 37 | # %% 3. Methods with Parameters 38 | # Explanation: Methods can take additional parameters for complex logic. 39 | # Example: 40 | class Product: 41 | def __init__(self, name, price): 42 | self.name = name 43 | self.price = price 44 | def calculate_total(self, quantity): 45 | return self.price * quantity 46 | 47 | smartphone = Product("Smartphone X", 699.99) 48 | total = smartphone.calculate_total(2) 49 | print(f"Total for 2 units: ${total:.2f}") 50 | # Output: Total for 2 units: $1399.98 51 | 52 | # %% Notes 53 | # Notes: 54 | # - Methods define object behavior, used in ML for model operations or web apps for business logic. 55 | # - Always include 'self' as first parameter in instance methods. 56 | # - Methods can return values or modify object state. -------------------------------------------------------------------------------- /Core Python Foundations/06 Object-Oriented Programming/04 Inheritance/Inheritance.py: -------------------------------------------------------------------------------- 1 | # %% Purpose 2 | # Python Object-Oriented Programming: Inheritance 3 | # Purpose: Inheritance allows a class to inherit attributes and methods from another class. 4 | # Key Features: Code reuse, hierarchical modeling. 5 | 6 | # %% 1. Basic Inheritance 7 | # Explanation: Child class inherits from parent using class Child(Parent). 8 | # Example: 9 | class Product: 10 | def __init__(self, name, price): 11 | self.name = name 12 | self.price = price 13 | def display(self): 14 | return f"{self.name}: ${self.price:.2f}" 15 | 16 | class Electronics(Product): 17 | pass 18 | 19 | laptop = Electronics("Laptop Pro", 999.99) 20 | print(laptop.display()) 21 | # Output: Laptop Pro: $999.99 22 | 23 | # %% 2. Extending Child Class 24 | # Explanation: Add or override methods/attributes in child class. 25 | # Example: 26 | class Product: 27 | def __init__(self, name, price): 28 | self.name = name 29 | self.price = price 30 | def display(self): 31 | return f"{self.name}: ${self.price:.2f}" 32 | 33 | class Electronics(Product): 34 | def __init__(self, name, price, warranty): 35 | super().__init__(name, price) 36 | self.warranty = warranty 37 | def display(self): 38 | return f"{self.name}: ${self.price:.2f}, Warranty: {self.warranty} years" 39 | 40 | smartphone = Electronics("Smartphone X", 699.99, 2) 41 | print(smartphone.display()) 42 | # Output: Smartphone X: $699.99, Warranty: 2 years 43 | 44 | # %% 3. Retail Scenario with Inheritance 45 | # Explanation: Model specialized products with inheritance. 46 | # Example: 47 | class Product: 48 | def __init__(self, name, price): 49 | self.name = name 50 | self.price = price 51 | def apply_discount(self, discount): 52 | self.price *= (1 - discount) 53 | 54 | class Appliance(Product): 55 | def __init__(self, name, price, power): 56 | super().__init__(name, price) 57 | self.power = power 58 | def display(self): 59 | return f"{self.name}: ${self.price:.2f}, Power: {self.power}W" 60 | 61 | blender = Appliance("Blender", 39.99, 500) 62 | blender.apply_discount(0.1) 63 | print(blender.display()) 64 | # Output: Blender: $35.99, Power: 500W 65 | 66 | # %% Notes 67 | # Notes: 68 | # - Use super() to call parent class methods/constructors. 69 | # - Inheritance promotes reuse in ML (e.g., model hierarchies) or web apps (e.g., user types). 70 | # - Avoid deep inheritance hierarchies for simplicity. -------------------------------------------------------------------------------- /Core Python Foundations/06 Object-Oriented Programming/05 Multiple Inheritance/Multiple Inheritance.py: -------------------------------------------------------------------------------- 1 | # %% Purpose 2 | # Python Object-Oriented Programming: Multiple Inheritance 3 | # Purpose: Multiple inheritance allows a class to inherit from multiple parent classes. 4 | # Key Features: Combines behaviors, complex hierarchies. 5 | 6 | # %% 1. Basic Multiple Inheritance 7 | # Explanation: Class inherits from multiple parents using class Child(Parent1, Parent2). 8 | # Example: 9 | class Product: 10 | def __init__(self, name, price): 11 | self.name = name 12 | self.price = price 13 | def display(self): 14 | return f"{self.name}: ${self.price:.2f}" 15 | 16 | class Discountable: 17 | def apply_discount(self, discount): 18 | self.price *= (1 - discount) 19 | 20 | class Electronics(Product, Discountable): 21 | pass 22 | 23 | laptop = Electronics("Laptop Pro", 999.99) 24 | laptop.apply_discount(0.1) 25 | print(laptop.display()) 26 | # Output: Laptop Pro: $899.99 27 | 28 | # %% 2. Resolving Method Conflicts 29 | # Explanation: Method Resolution Order (MRO) determines which parent method is called. 30 | # Example: 31 | class Product: 32 | def display(self): 33 | return "Product display" 34 | 35 | class Warranty: 36 | def display(self): 37 | return "Warranty display" 38 | 39 | class Smartphone(Product, Warranty): 40 | pass 41 | 42 | smartphone = Smartphone() 43 | print(smartphone.display()) 44 | print(Smartphone.__mro__) 45 | # Output: Product display 46 | # (, , , ) 47 | 48 | # %% 3. Retail Scenario with Multiple Inheritance 49 | # Explanation: Combine product and promotional features. 50 | # Example: 51 | class Product: 52 | def __init__(self, name, price): 53 | self.name = name 54 | self.price = price 55 | def display(self): 56 | return f"{self.name}: ${self.price:.2f}" 57 | 58 | class Promotable: 59 | def __init__(self, promotion): 60 | self.promotion = promotion 61 | def get_promo(self): 62 | return f"Promotion: {self.promotion}" 63 | 64 | class Appliance(Product, Promotable): 65 | def __init__(self, name, price, promotion): 66 | Product.__init__(self, name, price) 67 | Promotable.__init__(self, promotion) 68 | 69 | blender = Appliance("Blender", 39.99, "10% off") 70 | print(blender.display()) 71 | print(blender.get_promo()) 72 | # Output: Blender: $39.99 73 | # Promotion: 10% off 74 | 75 | # %% Notes 76 | # Notes: 77 | # - Use multiple inheritance sparingly to avoid complexity. 78 | # - Check MRO with __mro__ or mro() to understand method resolution. 79 | # - Useful in ML for combining model features or web apps for mixing behaviors. -------------------------------------------------------------------------------- /Core Python Foundations/06 Object-Oriented Programming/06 Encapsulation/Encapsulation.py: -------------------------------------------------------------------------------- 1 | # %% Purpose 2 | # Python Object-Oriented Programming: Encapsulation 3 | # Purpose: Encapsulation restricts access to attributes/methods, protecting data integrity. 4 | # Key Features: Private attributes (using _ or __), getter/setter methods. 5 | 6 | # %% 1. Private Attributes with Single Underscore 7 | # Explanation: Single underscore (_) indicates "protected" (convention, not enforced). 8 | # Example: 9 | class Product: 10 | def __init__(self, name, price): 11 | self.name = name 12 | self._price = price # Protected attribute 13 | def get_price(self): 14 | return self._price 15 | 16 | laptop = Product("Laptop Pro", 999.99) 17 | print(f"Price: ${laptop.get_price():.2f}") 18 | # Output: Price: $999.99 19 | print("Accessing _price:", laptop._price) # Accessible but discouraged 20 | # Output: Accessing _price: 999.99 21 | 22 | # %% 2. Private Attributes with Double Underscore 23 | # Explanation: Double underscore (__) triggers name mangling for stronger protection. 24 | # Example: 25 | class Product: 26 | def __init__(self, name, price): 27 | self.name = name 28 | self.__price = price # Private attribute 29 | def get_price(self): 30 | return self.__price 31 | def set_price(self, price): 32 | if price >= 0: 33 | self.__price = price 34 | else: 35 | raise ValueError("Price cannot be negative") 36 | 37 | smartphone = Product("Smartphone X", 699.99) 38 | print(f"Price: ${smartphone.get_price():.2f}") 39 | smartphone.set_price(649.99) 40 | print(f"Updated price: ${smartphone.get_price():.2f}") 41 | # Output: Price: $699.99 42 | # Updated price: $649.99 43 | 44 | # %% 3. Retail Scenario with Encapsulation 45 | # Explanation: Protect sensitive data like stock in a retail context. 46 | # Example: 47 | class Product: 48 | def __init__(self, name, stock): 49 | self.name = name 50 | self.__stock = stock 51 | def get_stock(self): 52 | return self.__stock 53 | def update_stock(self, amount): 54 | if amount >= 0: 55 | self.__stock = amount 56 | else: 57 | raise ValueError("Stock cannot be negative") 58 | 59 | blender = Product("Blender", 20) 60 | print(f"Stock: {blender.get_stock()}") 61 | blender.update_stock(30) 62 | print(f"Updated stock: {blender.get_stock()}") 63 | # Output: Stock: 20 64 | # Updated stock: 30 65 | 66 | # %% Notes 67 | # Notes: 68 | # - Encapsulation ensures data safety in ML (e.g., model parameters) or web apps (e.g., user data). 69 | # - Use _ for convention-based protection, __ for stricter access control. 70 | # - Getter/setter methods validate data before modification. -------------------------------------------------------------------------------- /Core Python Foundations/06 Object-Oriented Programming/07 Polymorphism/Polymorphism.py: -------------------------------------------------------------------------------- 1 | # %% Purpose 2 | # Python Object-Oriented Programming: Polymorphism 3 | # Purpose: Polymorphism allows different classes to be treated via a common interface. 4 | # Key Features: Method overriding, flexible design. 5 | 6 | # %% 1. Method Overriding 7 | # Explanation: Child class redefines a parent class method. 8 | # Example: 9 | class Product: 10 | def __init__(self, name, price): 11 | self.name = name 12 | self.price = price 13 | def display(self): 14 | return f"{self.name}: ${self.price:.2f}" 15 | 16 | class Electronics(Product): 17 | def display(self): 18 | return f"Electronics - {self.name}: ${self.price:.2f}" 19 | 20 | laptop = Electronics("Laptop Pro", 999.99) 21 | print(laptop.display()) 22 | # Output: Electronics - Laptop Pro: $999.99 23 | 24 | # %% 2. Polymorphic Behavior 25 | # Explanation: Use a common interface for different classes. 26 | # Example: 27 | class Product: 28 | def __init__(self, name, price): 29 | self.name = name 30 | self.price = price 31 | def get_details(self): 32 | return f"{self.name}: ${self.price:.2f}" 33 | 34 | class Appliance(Product): 35 | def __init__(self, name, price, power): 36 | super().__init__(name, price) 37 | self.power = power 38 | def get_details(self): 39 | return f"{self.name}: ${self.price:.2f}, Power: {self.power}W" 40 | 41 | products = [Product("Mouse", 29.99), Appliance("Blender", 39.99, 500)] 42 | for product in products: 43 | print(product.get_details()) 44 | # Output: Mouse: $29.99 45 | # Blender: $39.99, Power: 500W 46 | 47 | # %% 3. Retail Scenario with Polymorphism 48 | # Explanation: Process different product types uniformly. 49 | # Example: 50 | class Product: 51 | def __init__(self, name, price): 52 | self.name = name 53 | self.price = price 54 | def apply_discount(self): 55 | return self.price * 0.9 56 | 57 | class Electronics(Product): 58 | def apply_discount(self): 59 | return self.price * 0.85 # Special discount for electronics 60 | 61 | items = [Product("Coffee Maker", 49.99), Electronics("Smartphone", 699.99)] 62 | for item in items: 63 | print(f"Discounted price for {item.name}: ${item.apply_discount():.2f}") 64 | # Output: Discounted price for Coffee Maker: $44.99 65 | # Discounted price for Smartphone: $594.99 66 | 67 | # %% Notes 68 | # Notes: 69 | # - Polymorphism enables flexible code in ML (e.g., model interfaces) or web apps (e.g., rendering different entities). 70 | # - Use method overriding to customize behavior. 71 | # - Ensure common method names for polymorphic behavior. -------------------------------------------------------------------------------- /Core Python Foundations/06 Object-Oriented Programming/08 Abstract Classes/Abstract Classes.py: -------------------------------------------------------------------------------- 1 | # %% Purpose 2 | # Python Object-Oriented Programming: Abstract Classes 3 | # Purpose: Abstract classes define methods that must be implemented by child classes. 4 | # Key Features: Enforces interface, prevents instantiation. 5 | 6 | # %% 1. Defining an Abstract Class 7 | # Explanation: Use abc module, ABC class, and @abstractmethod decorator. 8 | # Example: 9 | from abc import ABC, abstractmethod 10 | 11 | class Product(ABC): 12 | @abstractmethod 13 | def display(self): 14 | pass 15 | 16 | # Cannot instantiate Product 17 | # product = Product() # Error: Can't instantiate abstract class 18 | 19 | # %% 2. Implementing Abstract Methods 20 | # Explanation: Child class must implement all abstract methods. 21 | # Example: 22 | from abc import ABC, abstractmethod 23 | 24 | class Product(ABC): 25 | def __init__(self, name, price): 26 | self.name = name 27 | self.price = price 28 | @abstractmethod 29 | def display(self): 30 | pass 31 | 32 | class Electronics(Product): 33 | def display(self): 34 | return f"Electronics - {self.name}: ${self.price:.2f}" 35 | 36 | laptop = Electronics("Laptop Pro", 999.99) 37 | print(laptop.display()) 38 | # Output: Electronics - Laptop Pro: $999.99 39 | 40 | # %% 3. Retail Scenario with Abstract Class 41 | # Explanation: Enforce a discount policy across product types. 42 | # Example: 43 | from abc import ABC, abstractmethod 44 | 45 | class Product(ABC): 46 | def __init__(self, name, price): 47 | self.name = name 48 | self.price = price 49 | @abstractmethod 50 | def apply_discount(self): 51 | pass 52 | 53 | class Appliance(Product): 54 | def apply_discount(self): 55 | return self.price * 0.9 56 | 57 | blender = Appliance("Blender", 39.99) 58 | print(f"Discounted price: ${blender.apply_discount():.2f}") 59 | # Output: Discounted price: $35.99 60 | 61 | # %% Notes 62 | # Notes: 63 | # - Abstract classes ensure consistent interfaces in ML (e.g., model APIs) or web apps (e.g., entity handlers). 64 | # - Use abc module to enforce abstraction. 65 | # - Child classes must implement all abstract methods. -------------------------------------------------------------------------------- /Core Python Foundations/06 Object-Oriented Programming/09 Static Methods/Static Methods.py: -------------------------------------------------------------------------------- 1 | # %% Purpose 2 | # Python Object-Oriented Programming: Static Methods 3 | # Purpose: Static methods belong to a class, not instances, and don’t access instance data. 4 | # Key Features: Utility functions, no 'self' parameter. 5 | 6 | # %% 1. Defining a Static Method 7 | # Explanation: Use @staticmethod decorator, no 'self' or 'cls'. 8 | # Example: 9 | class Product: 10 | @staticmethod 11 | def calculate_tax(price): 12 | return price * 0.1 13 | 14 | tax = Product.calculate_tax(999.99) 15 | print(f"Tax: ${tax:.2f}") 16 | # Output: Tax: $99.99 17 | 18 | # %% 2. Static Method in Retail Context 19 | # Explanation: Use for class-level utilities (e.g., price formatting). 20 | # Example: 21 | class Product: 22 | @staticmethod 23 | def format_price(price): 24 | return f"${price:.2f}" 25 | 26 | def __init__(self, name, price): 27 | self.name = name 28 | self.price = price 29 | def display(self): 30 | return f"{self.name}: {Product.format_price(self.price)}" 31 | 32 | laptop = Product("Laptop Pro", 999.99) 33 | print(laptop.display()) 34 | print(Product.format_price(49.99)) 35 | # Output: Laptop Pro: $999.99 36 | # $49.99 37 | 38 | # %% 3. Combining with Instance Methods 39 | # Explanation: Static methods can be called from instance methods. 40 | # Example: 41 | class Product: 42 | @staticmethod 43 | def is_valid_price(price): 44 | return isinstance(price, (int, float)) and price >= 0 45 | def __init__(self, name, price): 46 | if not Product.is_valid_price(price): 47 | raise ValueError("Invalid price") 48 | self.name = name 49 | self.price = price 50 | 51 | blender = Product("Blender", 39.99) 52 | print(f"Product: {blender.name}, Price: ${blender.price:.2f}") 53 | # Output: Product: Blender, Price: $39.99 54 | 55 | # %% Notes 56 | # Notes: 57 | # - Static methods are class-level utilities, used in ML for helper functions or web apps for formatting. 58 | # - No access to instance or class state unless passed explicitly. 59 | # - Call via class or instance (e.g., Product.method() or obj.method()). -------------------------------------------------------------------------------- /Core Python Foundations/06 Object-Oriented Programming/10 Class Methods/Class Methods.py: -------------------------------------------------------------------------------- 1 | # %% Purpose 2 | # Python Object-Oriented Programming: Class Methods 3 | # Purpose: Class methods operate on the class itself, taking 'cls' as first parameter. 4 | # Key Features: Access class attributes, alternative constructors. 5 | 6 | # %% 1. Defining a Class Method 7 | # Explanation: Use @classmethod decorator, 'cls' refers to the class. 8 | # Example: 9 | class Product: 10 | store_name = "Tech Retail" 11 | @classmethod 12 | def get_store(cls): 13 | return cls.store_name 14 | 15 | print(Product.get_store()) 16 | # Output: Tech Retail 17 | 18 | # %% 2. Class Method as Alternative Constructor 19 | # Explanation: Create objects from alternative data formats. 20 | # Example: 21 | class Product: 22 | def __init__(self, name, price): 23 | self.name = name 24 | self.price = price 25 | @classmethod 26 | def from_string(cls, product_str): 27 | name, price = product_str.split(",") 28 | return cls(name, float(price)) 29 | 30 | laptop = Product.from_string("Laptop Pro,999.99") 31 | print(f"Product: {laptop.name}, Price: ${laptop.price:.2f}") 32 | # Output: Product: Laptop Pro, Price: $999.99 33 | 34 | # %% 3. Retail Scenario with Class Method 35 | # Explanation: Manage class-level data or create objects. 36 | # Example: 37 | class Product: 38 | discount_rate = 0.1 39 | def __init__(self, name, price): 40 | self.name = name 41 | self.price = price 42 | @classmethod 43 | def set_discount(cls, rate): 44 | cls.discount_rate = rate 45 | def apply_discount(self): 46 | return self.price * (1 - Product.discount_rate) 47 | 48 | blender = Product("Blender", 39.99) 49 | Product.set_discount(0.15) 50 | print(f"Discounted price: ${blender.apply_discount():.2f}") 51 | # Output: Discounted price: $33.99 52 | 53 | # %% Notes 54 | # Notes: 55 | # - Class methods operate on class state, used in ML for model configs or web apps for shared settings. 56 | # - Use 'cls' to access class attributes or create objects. 57 | # - Alternative constructors enhance flexibility. -------------------------------------------------------------------------------- /Core Python Foundations/07 Modules and Packages/01 Importing Modules/Importing Modules.py: -------------------------------------------------------------------------------- 1 | # %% Purpose 2 | # Python Modules and Packages: Importing Modules 3 | # Purpose: Importing modules allows reusing code from Python's standard library or third-party packages. 4 | # Key Features: Access functions, classes, and variables defined in other files. 5 | 6 | # %% 1. Basic Import 7 | # Explanation: Use 'import' to access a module's contents. 8 | # Example: 9 | import math 10 | 11 | price = 49.99 12 | rounded_price = math.ceil(price) 13 | print(f"Rounded price: ${rounded_price:.2f}") 14 | # Output: Rounded price: $50.00 15 | 16 | # %% 2. Importing Specific Items 17 | # Explanation: Use 'from module import item' to import specific functions or classes. 18 | # Example: 19 | from random import randint 20 | 21 | # Simulate random stock levels for a product 22 | stock = randint(10, 100) 23 | print(f"Random stock level: {stock}") 24 | # Output: Random stock level: (random number between 10 and 100) 25 | 26 | # %% 3. Using Aliases and Retail Scenario 27 | # Explanation: Use 'import as' for shorter names; apply to retail data processing. 28 | # Example: 29 | import datetime as dt 30 | 31 | # Record order timestamp 32 | order_time = dt.datetime.now() 33 | print(f"Order placed at: {order_time.strftime('%Y-%m-%d %H:%M:%S')}") 34 | # Output: Order placed at: 2025-04-25 HH:MM:SS (current time) 35 | 36 | # %% Notes 37 | # Notes: 38 | # - Use imports to leverage Python’s standard library or third-party packages in ML (e.g., NumPy) or web apps (e.g., Flask). 39 | # - Avoid 'from module import *' to prevent namespace pollution. 40 | # - Modules are loaded once per session, improving performance. -------------------------------------------------------------------------------- /Core Python Foundations/07 Modules and Packages/02 Creating Modules/Creating Modules.py: -------------------------------------------------------------------------------- 1 | # %% Purpose 2 | # Python Modules and Packages: Creating Modules 3 | # Purpose: Creating modules organizes code into reusable files. 4 | # Key Features: Encapsulates functions, classes, or variables in a .py file. 5 | 6 | # %% Note 7 | # Note: This file demonstrates creating and using a module. In practice, the module would be a separate .py file. 8 | 9 | # %% Simulated Module Content (e.g., retail_utils.py) 10 | """ 11 | # retail_utils.py 12 | def calculate_discount(price, rate): 13 | return price * (1 - rate) 14 | 15 | def check_stock(stock): 16 | return "Low" if stock < 50 else "Sufficient" 17 | 18 | class Product: 19 | def __init__(self, name, price): 20 | self.name = name 21 | self.price = price 22 | """ 23 | 24 | # %% 1. Importing a Custom Module 25 | # Explanation: Import a module from the same directory. 26 | # Example: 27 | # Assuming retail_utils.py exists 28 | try: 29 | import retail_utils 30 | price = 999.99 31 | discounted_price = retail_utils.calculate_discount(price, 0.1) 32 | print(f"Discounted price: ${discounted_price:.2f}") 33 | except ImportError: 34 | print("Error: retail_utils module not found (simulated)") 35 | # Output: Discounted price: $899.99 (if module exists) 36 | 37 | # %% 2. Using Module Functions and Classes 38 | # Explanation: Access module contents like functions or classes. 39 | # Example: 40 | try: 41 | import retail_utils 42 | stock = 30 43 | status = retail_utils.check_stock(stock) 44 | print(f"Stock status: {status}") 45 | product = retail_utils.Product("Laptop", 999.99) 46 | print(f"Product: {product.name}, Price: ${product.price:.2f}") 47 | except ImportError: 48 | print("Error: retail_utils module not found (simulated)") 49 | # Output: Stock status: Low 50 | # Product: Laptop, Price: $999.99 (if module exists) 51 | 52 | # %% 3. Retail Scenario with Custom Module 53 | # Explanation: Use a module for retail calculations. 54 | # Example: 55 | try: 56 | import retail_utils 57 | order = {"name": "Smartphone", "price": 699.99, "stock": 100} 58 | discounted = retail_utils.calculate_discount(order["price"], 0.05) 59 | stock_status = retail_utils.check_stock(order["stock"]) 60 | print(f"Order: {order['name']}, Discounted: ${discounted:.2f}, Stock: {stock_status}") 61 | except ImportError: 62 | print("Error: retail_utils module not found (simulated)") 63 | # Output: Order: Smartphone, Discounted: $664.99, Stock: Sufficient (if module exists) 64 | 65 | # %% Notes 66 | # Notes: 67 | # - Save module code in a separate .py file in the same directory or a package. 68 | # - Use in ML for organizing data preprocessing (e.g., feature engineering modules) or web apps for utilities (e.g., API helpers). 69 | # - Handle ImportError for robust code, especially in production. -------------------------------------------------------------------------------- /Core Python Foundations/07 Modules and Packages/02 Creating Modules/retail_utils.py: -------------------------------------------------------------------------------- 1 | def calculate_discount(price, rate): 2 | return price * (1 - rate) 3 | 4 | def check_stock(stock): 5 | return "Low" if stock < 50 else "Sufficient" 6 | 7 | class Product: 8 | def __init__(self, name, price): 9 | self.name = name 10 | self.price = price -------------------------------------------------------------------------------- /Core Python Foundations/07 Modules and Packages/03 Packages/Packages.py: -------------------------------------------------------------------------------- 1 | # %% Purpose 2 | # Python Modules and Packages: Packages 3 | # Purpose: Packages organize related modules into a directory with an __init__.py file. 4 | # Key Features: Hierarchical structure, namespace management. 5 | 6 | # %% Note 7 | # Note: This file simulates a package structure. In practice, create a directory with __init__.py. 8 | 9 | # %% Simulated Package Structure 10 | """ 11 | retail_package/ 12 | __init__.py 13 | products.py 14 | orders.py 15 | """ 16 | """ 17 | # retail_package/products.py 18 | def calculate_discount(price, rate): 19 | return price * (1 - rate) 20 | """ 21 | """ 22 | # retail_package/orders.py 23 | class Order: 24 | def __init__(self, order_id, total): 25 | self.order_id = order_id 26 | self.total = total 27 | """ 28 | """ 29 | # retail_package/__init__.py 30 | # (Empty or with imports) 31 | """ 32 | 33 | # %% 1. Importing from a Package 34 | # Explanation: Use dot notation to access modules in a package. 35 | # Example: 36 | try: 37 | from retail_package import products 38 | price = 999.99 39 | discounted = products.calculate_discount(price, 0.1) 40 | print(f"Discounted price: ${discounted:.2f}") 41 | except ImportError: 42 | print("Error: retail_package not found (simulated)") 43 | # Output: Discounted price: $899.99 (if package exists) 44 | 45 | # %% 2. Using Package Modules 46 | # Explanation: Import specific modules or classes from a package. 47 | # Example: 48 | try: 49 | from retail_package import orders 50 | order = orders.Order(101, 1999.98) 51 | print(f"Order: {order.order_id}, Total: ${order.total:.2f}") 52 | except ImportError: 53 | print("Error: retail_package not found (simulated)") 54 | # Output: Order: 101, Total: $1999.98 (if package exists) 55 | 56 | # %% 3. Retail Scenario with Package 57 | # Explanation: Use a package to manage retail operations. 58 | # Example: 59 | try: 60 | from retail_package.products import calculate_discount 61 | from retail_package.orders import Order 62 | product = {"name": "Laptop", "price": 999.99} 63 | order = Order(102, calculate_discount(product["price"], 0.05)) 64 | print(f"Order {order.order_id}: Total ${order.total:.2f}") 65 | except ImportError: 66 | print("Error: retail_package not found (simulated)") 67 | # Output: Order 102: Total $949.99 (if package exists) 68 | 69 | # %% Notes 70 | # Notes: 71 | # - Packages require an __init__.py file (can be empty) to be recognized. 72 | # - Use in ML for organizing large projects (e.g., data preprocessing packages) or web apps for modular APIs. 73 | # - Handle ImportError for missing packages, especially with third-party dependencies. -------------------------------------------------------------------------------- /Core Python Foundations/07 Modules and Packages/03 Packages/retail_package/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rohanmistry231/Python-Interview-Preparation/ffbc9f1ca28d0cfc66b351509ec6962965dc29b9/Core Python Foundations/07 Modules and Packages/03 Packages/retail_package/__init__.py -------------------------------------------------------------------------------- /Core Python Foundations/07 Modules and Packages/03 Packages/retail_package/orders.py: -------------------------------------------------------------------------------- 1 | class Order: 2 | def __init__(self, order_id, total): 3 | self.order_id = order_id 4 | self.total = total -------------------------------------------------------------------------------- /Core Python Foundations/07 Modules and Packages/03 Packages/retail_package/products.py: -------------------------------------------------------------------------------- 1 | def calculate_discount(price, rate): 2 | return price * (1 - rate) -------------------------------------------------------------------------------- /Core Python Foundations/07 Modules and Packages/04 Standard Library/Standard Library - datetime.py: -------------------------------------------------------------------------------- 1 | # %% Purpose 2 | # Python Modules and Packages: Standard Library - datetime 3 | # Purpose: The datetime module handles dates, times, and time intervals. 4 | # Key Features: Date arithmetic, formatting, time zones. 5 | 6 | # %% 1. Working with Current Date and Time 7 | # Explanation: Use datetime.now() to get current timestamp. 8 | # Example: 9 | import datetime 10 | 11 | order_time = datetime.datetime.now() 12 | print(f"Order placed at: {order_time.strftime('%Y-%m-%d %H:%M:%S')}") 13 | # Output: Order placed at: 2025-04-25 HH:MM:SS (current time) 14 | 15 | # %% 2. Date Arithmetic 16 | # Explanation: Perform operations like adding days or calculating differences. 17 | # Example: 18 | import datetime 19 | 20 | # Calculate delivery date (3 days from now) 21 | order_date = datetime.datetime.now() 22 | delivery_date = order_date + datetime.timedelta(days=3) 23 | print(f"Expected delivery: {delivery_date.strftime('%Y-%m-%d')}") 24 | # Output: Expected delivery: 2025-04-28 (3 days from now) 25 | 26 | # %% 3. Retail Scenario with datetime 27 | # Explanation: Track order timestamps and deadlines. 28 | # Example: 29 | import datetime 30 | 31 | # Check if order is within return period (30 days) 32 | order_date = datetime.datetime(2025, 3, 15) 33 | today = datetime.datetime.now() 34 | days_since_order = (today - order_date).days 35 | return_status = "Eligible" if days_since_order <= 30 else "Not eligible" 36 | print(f"Order from {order_date.strftime('%Y-%m-%d')}: Return {return_status}") 37 | # Output: Order from 2025-03-15: Return Eligible (if within 30 days) 38 | 39 | # %% Notes 40 | # Notes: 41 | # - datetime is critical in ML for time-series data or web apps for logging (e.g., order timestamps). 42 | # - Use strftime() for formatting, strptime() for parsing strings. 43 | # - Handle timezone-aware datetimes with pytz for production apps. -------------------------------------------------------------------------------- /Core Python Foundations/07 Modules and Packages/04 Standard Library/Standard Library - math.py: -------------------------------------------------------------------------------- 1 | # %% Purpose 2 | # Python Modules and Packages: Standard Library - math 3 | # Purpose: The math module provides mathematical functions and constants. 4 | # Key Features: Trigonometric, logarithmic, and arithmetic operations. 5 | 6 | # %% 1. Basic math Functions 7 | # Explanation: Use functions like ceil(), floor(), and sqrt(). 8 | # Example: 9 | import math 10 | 11 | price = 49.99 12 | ceiling_price = math.ceil(price) 13 | square_root = math.sqrt(price) 14 | print(f"Ceiling price: ${ceiling_price:.2f}, Square root: {square_root:.2f}") 15 | # Output: Ceiling price: $50.00, Square root: 7.07 16 | 17 | # %% 2. Using Constants 18 | # Explanation: Access constants like pi and e. 19 | # Example: 20 | import math 21 | 22 | # Calculate area of a circular product display 23 | radius = 5 24 | area = math.pi * radius ** 2 25 | print(f"Display area: {area:.2f} square units") 26 | # Output: Display area: 78.54 square units 27 | 28 | # %% 3. Retail Scenario with math 29 | # Explanation: Apply math functions for pricing calculations. 30 | # Example: 31 | import math 32 | 33 | items = [99.99, 149.99, 199.99] 34 | # Round prices to nearest 10 35 | rounded_prices = [math.ceil(price / 10) * 10 for price in items] 36 | print(f"Rounded prices: {rounded_prices}") 37 | # Output: Rounded prices: [100, 150, 200] 38 | 39 | # %% Notes 40 | # Notes: 41 | # - math module is useful in ML for numerical computations (e.g., distance metrics) or web apps for pricing. 42 | # - Functions expect numeric inputs; handle errors with try-except (e.g., math.sqrt(-1)). 43 | # - Use math for precise floating-point calculations. -------------------------------------------------------------------------------- /Core Python Foundations/07 Modules and Packages/04 Standard Library/Standard Library - math_projects.py: -------------------------------------------------------------------------------- 1 | # math Projects 2 | # Purpose: Apply math module through 10 retail-themed projects. 3 | # Structure: Each project is separated by %% and includes description, tasks, and solution code. 4 | # Note: Solutions use simulated inputs for reproducibility and match the updated base file outputs. 5 | 6 | # %% Project 1: Price Ceiling Calculator 7 | # Difficulty: Basic 8 | # Description: Round up a product price to the nearest integer. 9 | # Objective: Practice basic math functions. 10 | # Tasks: 11 | # - Import math and use ceil() on a price. 12 | # - Print the ceiling price. 13 | # Expected Output: Ceiling price: $30.00 14 | import math 15 | 16 | price = 29.99 17 | ceiling_price = math.ceil(price) 18 | print(f"Ceiling price: ${ceiling_price:.2f}") 19 | 20 | # %% Project 2: Price Flooring Calculator 21 | # Difficulty: Basic 22 | # Description: Round down a product price to the nearest integer. 23 | # Objective: Practice basic math functions. 24 | # Tasks: 25 | # - Import math and use floor() on a price. 26 | # - Print the floored price. 27 | # Expected Output: Floored price: $29.00 28 | import math 29 | 30 | price = 29.99 31 | floored_price = math.floor(price) 32 | print(f"Floored price: ${floored_price:.2f}") 33 | 34 | # %% Project 3: Display Area Calculator 35 | # Difficulty: Basic 36 | # Description: Calculate the area of a circular product display. 37 | # Objective: Practice using math constants. 38 | # Tasks: 39 | # - Import math and calculate the area using pi and radius 3. 40 | # - Print the area. 41 | # Expected Output: Display area: 28.27 square units 42 | import math 43 | 44 | radius = 3 45 | area = math.pi * radius ** 2 46 | print(f"Display area: {area:.2f} square units") 47 | 48 | # %% Project 4: Logarithmic Stock Analysis 49 | # Difficulty: Intermediate 50 | # Description: Calculate the logarithm of a stock quantity. 51 | # Objective: Practice logarithmic functions. 52 | # Tasks: 53 | # - Import math and use log() on a stock value. 54 | # - Print the logarithm. 55 | # Expected Output: Stock logarithm: 4.61 56 | import math 57 | 58 | stock = 100 59 | log_stock = math.log(stock) 60 | print(f"Stock logarithm: {log_stock:.2f}") 61 | 62 | # %% Project 5: Power-Based Discount 63 | # Difficulty: Intermediate 64 | # Description: Apply a discount using a power function. 65 | # Objective: Practice power calculations. 66 | # Tasks: 67 | # - Import math and use pow() to calculate a discounted price. 68 | # - Print the discounted price. 69 | # Expected Output: Discounted price: $90.00 70 | import math 71 | 72 | price = 100 73 | discount_factor = 0.9 74 | discounted_price = math.pow(price, 1) * discount_factor 75 | print(f"Discounted price: ${discounted_price:.2f}") 76 | 77 | # %% Project 6: Nearest Ten Rounder 78 | # Difficulty: Intermediate 79 | # Description: Round a price to the nearest 10. 80 | # Objective: Practice combining math functions. 81 | # Tasks: 82 | # - Import math and round a price to the nearest 10 using ceil(). 83 | # - Print the rounded price. 84 | # Expected Output: Rounded price: $100.00 85 | import math 86 | 87 | price = 95.99 88 | rounded_price = math.ceil(price / 10) * 10 89 | print(f"Rounded price: ${rounded_price:.2f}") 90 | 91 | # %% Project 7: Factorial Quantity Calculator 92 | # Difficulty: Intermediate 93 | # Description: Calculate the factorial of a small order quantity. 94 | # Objective: Practice factorial calculations. 95 | # Tasks: 96 | # - Import math and use factorial() on a quantity. 97 | # - Print the factorial. 98 | # Expected Output: Order factorial: 120 99 | import math 100 | 101 | quantity = 5 102 | factorial = math.factorial(quantity) 103 | print(f"Order factorial: {factorial}") 104 | 105 | # %% Project 8: Trigonometric Display Angle 106 | # Difficulty: Advanced 107 | # Description: Calculate the sine of an angle for a product display. 108 | # Objective: Practice trigonometric functions. 109 | # Tasks: 110 | # - Import math and calculate sin(30 degrees). 111 | # - Print the sine value. 112 | # Expected Output: Display sine: 0.50 113 | import math 114 | 115 | angle_degrees = 30 116 | angle_radians = math.radians(angle_degrees) 117 | sine_value = math.sin(angle_radians) 118 | print(f"Display sine: {sine_value:.2f}") 119 | 120 | # %% Project 9: Exponential Growth Forecast 121 | # Difficulty: Advanced 122 | # Description: Forecast sales growth using an exponential function. 123 | # Objective: Practice exponential calculations. 124 | # Tasks: 125 | # - Import math and use exp() to model sales growth. 126 | # - Print the forecasted sales. 127 | # Expected Output: Forecasted sales: $271.83 128 | import math 129 | 130 | initial_sales = 100 131 | growth_rate = 1 132 | forecasted_sales = initial_sales * math.exp(growth_rate) 133 | print(f"Forecasted sales: ${forecasted_sales:.2f}") 134 | 135 | # %% Project 10: Comprehensive Pricing System 136 | # Difficulty: Advanced 137 | # Description: Combine multiple math functions for pricing calculations. 138 | # Objective: Practice integrating math functions. 139 | # Tasks: 140 | # - Import math and calculate ceiling, square root, and rounded price. 141 | # - Print all results. 142 | # Expected Output: Ceiling: $100.00, Sqrt: 9.95, Rounded: $100.00 143 | import math 144 | 145 | price = 99.49 146 | ceiling = math.ceil(price) 147 | sqrt_price = math.sqrt(price) 148 | rounded = math.ceil(price / 10) * 10 149 | print(f"Ceiling: ${ceiling:.2f}, Sqrt: {sqrt_price:.2f}, Rounded: ${rounded:.2f}") -------------------------------------------------------------------------------- /Core Python Foundations/07 Modules and Packages/04 Standard Library/Standard Library - os.py: -------------------------------------------------------------------------------- 1 | # %% Purpose 2 | # Python Modules and Packages: Standard Library - os 3 | # Purpose: The os module interacts with the operating system (e.g., file handling, directories). 4 | # Key Features: File operations, path management, environment variables. 5 | 6 | # %% 1. Working with Directories 7 | # Explanation: Use os.getcwd() and os.listdir() for directory operations. 8 | # Example: 9 | import os 10 | 11 | current_dir = os.getcwd() 12 | print(f"Current directory: {current_dir}") 13 | files = os.listdir(current_dir) 14 | print(f"Files in directory: {files}") 15 | # Output: Current directory: (current path) 16 | # Files in directory: (list of files, e.g., ['script.py']) 17 | 18 | # %% 2. File Path Handling 19 | # Explanation: Use os.path for cross-platform path manipulation. 20 | # Example: 21 | import os 22 | 23 | # Create a path for a retail database file 24 | db_file = os.path.join("data", "retail.db") 25 | print(f"Database file path: {db_file}") 26 | exists = os.path.exists(db_file) 27 | print(f"File exists: {exists}") 28 | # Output: Database file path: data/retail.db 29 | # File exists: False (unless file exists) 30 | 31 | # %% 3. Retail Scenario with os 32 | # Explanation: Manage retail data files (e.g., product CSVs). 33 | # Example: 34 | import os 35 | 36 | # Check for product data directory and create if missing 37 | data_dir = "product_data" 38 | if not os.path.exists(data_dir): 39 | os.makedirs(data_dir) 40 | print(f"Created directory: {data_dir}") 41 | else: 42 | print(f"Directory exists: {data_dir}") 43 | # Output: Created directory: product_data (if not exists) 44 | 45 | # %% Notes 46 | # Notes: 47 | # - os is essential in ML for file handling (e.g., datasets) or web apps for managing static files. 48 | # - Use os.path for platform-independent paths (e.g., Windows vs. Linux). 49 | # - Handle exceptions (e.g., PermissionError) for robust file operations. -------------------------------------------------------------------------------- /Core Python Foundations/07 Modules and Packages/04 Standard Library/Standard Library - random.py: -------------------------------------------------------------------------------- 1 | # %% Purpose 2 | # Python Modules and Packages: Standard Library - random 3 | # Purpose: The random module generates pseudo-random numbers and selections. 4 | # Key Features: Random numbers, choices, shuffling. 5 | 6 | # %% 1. Generating Random Numbers 7 | # Explanation: Use randint() for integers, uniform() for floats. 8 | # Example: 9 | import random 10 | 11 | # Simulate random discount percentage 12 | discount = random.uniform(0.05, 0.2) 13 | price = 999.99 14 | discounted_price = price * (1 - discount) 15 | print(f"Random discount: {discount:.2%}, Discounted price: ${discounted_price:.2f}") 16 | # Output: Random discount: (e.g., 12.34%), Discounted price: (e.g., $876.65) 17 | 18 | # %% 2. Random Selection 19 | # Explanation: Use choice() or sample() for selecting items. 20 | # Example: 21 | import random 22 | 23 | products = ["Laptop", "Smartphone", "Coffee Maker"] 24 | featured_product = random.choice(products) 25 | print(f"Featured product: {featured_product}") 26 | # Output: Featured product: (random product) 27 | 28 | # %% 3. Retail Scenario with random 29 | # Explanation: Simulate random stock or promotional offers. 30 | # Example: 31 | import random 32 | 33 | # Simulate random stock levels for multiple products 34 | stock_levels = {product: random.randint(10, 100) for product in ["Mouse", "Keyboard"]} 35 | print(f"Random stock levels: {stock_levels}") 36 | # Output: Random stock levels: {'Mouse': (random), 'Keyboard': (random)} 37 | 38 | # %% Notes 39 | # Notes: 40 | # - random is pseudo-random; use random.seed() for reproducibility in ML (e.g., data splitting). 41 | # - Useful in web apps for random promotions or A/B testing. 42 | # - Avoid in cryptographic applications (use secrets module instead). -------------------------------------------------------------------------------- /Core Python Foundations/07 Modules and Packages/04 Standard Library/Standard Library - sys.py: -------------------------------------------------------------------------------- 1 | # %% Purpose 2 | # Python Modules and Packages: Standard Library - sys 3 | # Purpose: The sys module provides system-specific parameters and functions. 4 | # Key Features: Command-line arguments, Python version, exit program. 5 | 6 | # %% 1. Accessing System Information 7 | # Explanation: Use sys.version and sys.platform for system details. 8 | # Example: 9 | import sys 10 | 11 | print(f"Python version: {sys.version}") 12 | print(f"Platform: {sys.platform}") 13 | # Output: Python version: (e.g., 3.11.4 ...) 14 | # Platform: (e.g., win32 or linux) 15 | 16 | # %% 2. Command-Line Arguments 17 | # Explanation: sys.argv contains command-line arguments. 18 | # Example: 19 | import sys 20 | 21 | # Simulate running: python script.py Laptop 999.99 22 | # sys.argv = ["script.py", "Laptop", "999.99"] # Simulated for demo 23 | try: 24 | if len(sys.argv) >= 3: 25 | product_name = sys.argv[1] 26 | price = float(sys.argv[2]) 27 | print(f"Product: {product_name}, Price: ${price:.2f}") 28 | else: 29 | print("Provide product name and price as arguments") 30 | except ValueError: 31 | print("Invalid price format") 32 | # Output: Product: Laptop, Price: $999.99 (if args provided) 33 | # Note: Run as 'python script.py Laptop 999.99' in practice 34 | 35 | # %% 3. Retail Scenario with sys 36 | # Explanation: Exit program if invalid retail data is provided. 37 | # Example: 38 | import sys 39 | 40 | # Simulate checking retail script arguments 41 | # sys.argv = ["script.py", "Smartphone", "-10"] # Simulated 42 | try: 43 | if len(sys.argv) >= 3: 44 | name = sys.argv[1] 45 | price = float(sys.argv[2]) 46 | if price < 0: 47 | print("Error: Negative price") 48 | sys.exit(1) # Exit with error code 49 | print(f"Valid product: {name}, Price: ${price:.2f}") 50 | else: 51 | print("Error: Missing arguments") 52 | except ValueError: 53 | print("Error: Invalid price format") 54 | # Output: Error: Negative price (exits if price < 0) 55 | # Note: Run as 'python script.py Smartphone -10' in practice 56 | 57 | # %% Notes 58 | # Notes: 59 | # - sys is useful in ML for script configuration or web apps for runtime info. 60 | # - Use sys.exit() for controlled program termination. 61 | # - sys.argv[0] is the script name; arguments start at sys.argv[1]. -------------------------------------------------------------------------------- /Core Python Foundations/07 Modules and Packages/04 Standard Library/Standard Library - time.py: -------------------------------------------------------------------------------- 1 | # %% Purpose 2 | # Python Modules and Packages: Standard Library - time 3 | # Purpose: The time module provides time-related functions (e.g., delays, timestamps). 4 | # Key Features: Measure execution time, add delays, format time. 5 | 6 | # %% 1. Getting Current Time 7 | # Explanation: Use time.time() for Unix timestamp, time.ctime() for readable time. 8 | # Example: 9 | import time 10 | 11 | current_time = time.ctime() 12 | print(f"Current time: {current_time}") 13 | # Output: Current time: Fri Apr 25 HH:MM:SS 2025 (current time) 14 | 15 | # %% 2. Adding Delays 16 | # Explanation: Use time.sleep() to pause execution. 17 | # Example: 18 | import time 19 | 20 | print("Processing order...") 21 | time.sleep(2) # Simulate processing delay 22 | print("Order processed") 23 | # Output: Processing order... 24 | # (2-second pause) 25 | # Order processed 26 | 27 | # %% 3. Retail Scenario with time 28 | # Explanation: Measure time for retail operations (e.g., batch processing). 29 | # Example: 30 | import time 31 | 32 | # Simulate processing multiple orders 33 | orders = ["Order 101", "Order 102", "Order 103"] 34 | start_time = time.time() 35 | for order in orders: 36 | print(f"Processing {order}") 37 | time.sleep(1) # Simulate work 38 | end_time = time.time() 39 | print(f"Total processing time: {end_time - start_time:.2f} seconds") 40 | # Output: Processing Order 101 41 | # Processing Order 102 42 | # Processing Order 103 43 | # Total processing time: 3.01 seconds (approx) 44 | 45 | # %% Notes 46 | # Notes: 47 | # - time is useful in ML for profiling code or web apps for scheduling tasks. 48 | # - time.time() returns seconds since epoch (Jan 1, 1970); use for timing. 49 | # - For date handling, prefer datetime module. -------------------------------------------------------------------------------- /Core Python Foundations/08 File Handling/01 Reading Files/Reading Files.py: -------------------------------------------------------------------------------- 1 | # %% Purpose 2 | # Python File Handling: Reading Files 3 | # Purpose: Reading files allows accessing data stored in text files. 4 | # Key Features: Read entire files, read lines, handle file paths. 5 | 6 | # Note: Examples assume files exist or simulate file content for demonstration. 7 | 8 | # %% 1. Reading Entire File 9 | # Explanation: Use open() with 'r' mode to read file content. 10 | # Example: 11 | try: 12 | with open("products.txt", "r") as file: 13 | content = file.read() 14 | print("Products:\n", content) 15 | except FileNotFoundError: 16 | print("Simulated products.txt content:\nLaptop,999.99\nSmartphone,699.99") 17 | # Output (if file exists): Products: (file content) 18 | # Output (if file missing): Simulated products.txt content: Laptop,999.99 Smartphone,699.99 19 | 20 | # %% 2. Reading Line by Line 21 | # Explanation: Use readlines() or iterate over file object for line-by-line reading. 22 | # Example: 23 | try: 24 | with open("products.txt", "r") as file: 25 | lines = file.readlines() 26 | for line in lines: 27 | print("Product line:", line.strip()) 28 | except FileNotFoundError: 29 | print("Simulated line-by-line:\nProduct line: Laptop,999.99\nProduct line: Smartphone,699.99") 30 | # Output (if file exists): Product line: (each line) 31 | # Output (if file missing): Simulated line-by-line: Product line: Laptop,999.99 Product line: Smartphone,699.99 32 | 33 | # %% 3. Retail Scenario with Reading Files 34 | # Explanation: Read product data for retail processing. 35 | # Example: 36 | try: 37 | with open("products.txt", "r") as file: 38 | products = [line.strip().split(",") for line in file] 39 | for name, price in products: 40 | print(f"Product: {name}, Price: ${float(price):.2f}") 41 | except FileNotFoundError: 42 | print("Simulated retail data:\nProduct: Laptop, Price: $999.99\nProduct: Smartphone, Price: $699.99") 43 | except ValueError: 44 | print("Error: Invalid price format in file") 45 | # Output (if file exists): Product: Laptop, Price: $999.99 (etc.) 46 | # Output (if file missing): Simulated retail data: Product: Laptop, Price: $999.99 Product: Smartphone, Price: $699.99 47 | 48 | # %% Notes 49 | # Notes: 50 | # - Use 'with' statement to automatically close files, reducing resource leaks. 51 | # - Handle FileNotFoundError and other exceptions for robust file reading. 52 | # - Useful in ML for reading datasets or web apps for loading configurations. -------------------------------------------------------------------------------- /Core Python Foundations/08 File Handling/01 Reading Files/reading_files_projects.py: -------------------------------------------------------------------------------- 1 | # Reading Files Projects 2 | # Purpose: Apply file reading through 5 retail-themed projects. 3 | # Structure: Each project is separated by %% and includes description, tasks, and solution code. 4 | # Note: Solutions use simulated inputs for reproducibility and match the updated base file outputs. 5 | 6 | # %% Project 1: Read Inventory File 7 | # Difficulty: Basic 8 | # Description: Read the entire content of an inventory.txt file. 9 | # Objective: Practice reading entire file content. 10 | # Tasks: 11 | # - Import os for path handling and read inventory.txt using read(). 12 | # - Print the file content or simulate if missing. 13 | # Expected Output: Inventory: Laptop,999.99 Smartphone,699.99 14 | import os 15 | 16 | file_path = "inventory.txt" 17 | try: 18 | with open(file_path, "r") as file: 19 | content = file.read() 20 | print(f"Inventory: {content.strip()}") 21 | except FileNotFoundError: 22 | print("Inventory: Laptop,999.99 Smartphone,699.99") 23 | 24 | # %% Project 2: List Orders Line by Line 25 | # Difficulty: Basic 26 | # Description: Read orders.txt and print each order line. 27 | # Objective: Practice line-by-line reading. 28 | # Tasks: 29 | # - Read orders.txt using a file iterator. 30 | # - Print each line or simulate if missing. 31 | # Expected Output: Order: Order 101,1999.98 32 | # Order: Order 102,49.99 33 | file_path = "orders.txt" 34 | try: 35 | with open(file_path, "r") as file: 36 | for line in file: 37 | print(f"Order: {line.strip()}") 38 | except FileNotFoundError: 39 | print("Order: Order 101,1999.98") 40 | print("Order: Order 102,49.99") 41 | 42 | # %% Project 3: Extract Expensive Products 43 | # Difficulty: Intermediate 44 | # Description: Read products.txt and list products with price > 500. 45 | # Objective: Practice processing file data. 46 | # Tasks: 47 | # - Read products.txt, split lines, and filter products by price. 48 | # - Print product names or simulate if missing. 49 | # Expected Output: Expensive products: ['Laptop', 'Smartphone'] 50 | file_path = "products.txt" 51 | expensive_products = [] 52 | try: 53 | with open(file_path, "r") as file: 54 | for line in file: 55 | name, price = line.strip().split(",") 56 | if float(price) > 500: 57 | expensive_products.append(name) 58 | print(f"Expensive products: {expensive_products}") 59 | except FileNotFoundError: 60 | print("Expensive products: ['Laptop', 'Smartphone']") 61 | except ValueError: 62 | print("Error: Invalid price format") 63 | 64 | # %% Project 4: Count Customer Records 65 | # Difficulty: Intermediate 66 | # Description: Count the number of customer records in customers.txt. 67 | # Objective: Practice file iteration and counting. 68 | # Tasks: 69 | # - Read customers.txt and count non-empty lines. 70 | # - Print the count or simulate if missing. 71 | # Expected Output: Customer count: 2 72 | file_path = "customers.txt" 73 | count = 0 74 | try: 75 | with open(file_path, "r") as file: 76 | for line in file: 77 | if line.strip(): 78 | count += 1 79 | print(f"Customer count: {count}") 80 | except FileNotFoundError: 81 | print("Customer count: 2") 82 | 83 | # %% Project 5: Validate Product Data 84 | # Difficulty: Advanced 85 | # Description: Read products.txt and validate price formats. 86 | # Objective: Practice robust file reading with error handling. 87 | # Tasks: 88 | # - Read products.txt, check for valid float prices, and report invalid entries. 89 | # - Print valid products or simulate if missing. 90 | # Expected Output: Valid products: ['Laptop', 'Smartphone'] 91 | # Invalid entries: [] 92 | file_path = "products.txt" 93 | valid_products = [] 94 | invalid_entries = [] 95 | try: 96 | with open(file_path, "r") as file: 97 | for line in file: 98 | try: 99 | name, price = line.strip().split(",") 100 | float(price) 101 | valid_products.append(name) 102 | except ValueError: 103 | invalid_entries.append(line.strip()) 104 | print(f"Valid products: {valid_products}") 105 | print(f"Invalid entries: {invalid_entries}") 106 | except FileNotFoundError: 107 | print("Valid products: ['Laptop', 'Smartphone']") 108 | print("Invalid entries: []") -------------------------------------------------------------------------------- /Core Python Foundations/08 File Handling/02 Writing Files/Writing Files.py: -------------------------------------------------------------------------------- 1 | # %% Purpose 2 | # Python File Handling: Writing Files 3 | # Purpose: Writing files stores data in text files for persistence. 4 | # Key Features: Write, append, create files if they don’t exist. 5 | 6 | # %% 1. Writing to a New File 7 | # Explanation: Use open() with 'w' mode to write content, overwriting existing files. 8 | # Example: 9 | try: 10 | with open("output.txt", "w") as file: 11 | file.write("Laptop,999.99\nSmartphone,699.99") 12 | print("Data written to output.txt") 13 | except PermissionError: 14 | print("Error: Permission denied (simulated)") 15 | # Output: Data written to output.txt 16 | # File content: Laptop,999.99 Smartphone,699.99 17 | 18 | # %% 2. Appending to a File 19 | # Explanation: Use 'a' mode to append content without overwriting. 20 | # Example: 21 | try: 22 | with open("output.txt", "a") as file: 23 | file.write("\nCoffee Maker,49.99") 24 | print("Appended to output.txt") 25 | except PermissionError: 26 | print("Error: Permission denied (simulated)") 27 | # Output: Appended to output.txt 28 | # File content (after append): Laptop,999.99 Smartphone,699.99 Coffee Maker,49.99 29 | 30 | # %% 3. Retail Scenario with Writing Files 31 | # Explanation: Write retail order data to a file. 32 | # Example: 33 | orders = [ 34 | {"order_id": 101, "total": 1999.98}, 35 | {"order_id": 102, "total": 49.99} 36 | ] 37 | try: 38 | with open("orders.txt", "w") as file: 39 | for order in orders: 40 | file.write(f"Order {order['order_id']},${order['total']:.2f}\n") 41 | print("Orders written to orders.txt") 42 | except PermissionError: 43 | print("Error: Permission denied (simulated)") 44 | # Output: Orders written to orders.txt 45 | # File content: Order 101,$1999.98 Order 102,$49.99 46 | 47 | # %% Notes 48 | # Notes: 49 | # - 'w' overwrites files; 'a' appends to existing content. 50 | # - Use 'with' for safe file handling; handle PermissionError for restricted directories. 51 | # - Useful in ML for saving model outputs or web apps for logging user actions. -------------------------------------------------------------------------------- /Core Python Foundations/08 File Handling/02 Writing Files/writing_files_projects.py: -------------------------------------------------------------------------------- 1 | # Writing Files Projects 2 | # Purpose: Apply file writing through 5 retail-themed projects. 3 | # Structure: Each project is separated by %% and includes description, tasks, and solution code. 4 | # Note: Solutions use simulated inputs for reproducibility and match the updated base file outputs. 5 | 6 | # %% Project 1: Write Product Catalog 7 | # Difficulty: Basic 8 | # Description: Write a list of products to catalog.txt. 9 | # Objective: Practice basic file writing. 10 | # Tasks: 11 | # - Write two products to catalog.txt using 'w' mode. 12 | # - Print confirmation or handle errors. 13 | # Expected Output: Catalog written to catalog.txt 14 | products = ["Mouse,29.99", "Keyboard,59.99"] 15 | try: 16 | with open("catalog.txt", "w") as file: 17 | for product in products: 18 | file.write(f"{product}\n") 19 | print("Catalog written to catalog.txt") 20 | except PermissionError: 21 | print("Error: Permission denied (simulated)") 22 | 23 | # %% Project 2: Append Order Log 24 | # Difficulty: Basic 25 | # Description: Append a new order to orders_log.txt. 26 | # Objective: Practice file appending. 27 | # Tasks: 28 | # - Append one order to orders_log.txt using 'a' mode. 29 | # - Print confirmation or handle errors. 30 | # Expected Output: Order appended to orders_log.txt 31 | order = "Order 103,99.99" 32 | try: 33 | with open("orders_log.txt", "a") as file: 34 | file.write(f"{order}\n") 35 | print("Order appended to orders_log.txt") 36 | except PermissionError: 37 | print("Error: Permission denied (simulated)") 38 | 39 | # %% Project 3: Save Customer Data 40 | # Difficulty: Intermediate 41 | # Description: Write customer data with names and emails to customers.txt. 42 | # Objective: Practice structured file writing. 43 | # Tasks: 44 | # - Write a list of dictionaries to customers.txt. 45 | # - Print confirmation or handle errors. 46 | # Expected Output: Customers written to customers.txt 47 | customers = [ 48 | {"name": "Alice", "email": "alice@example.com"}, 49 | {"name": "Bob", "email": "bob@example.com"} 50 | ] 51 | try: 52 | with open("customers.txt", "w") as file: 53 | for customer in customers: 54 | file.write(f"{customer['name']},{customer['email']}\n") 55 | print("Customers written to customers.txt") 56 | except PermissionError: 57 | print("Error: Permission denied (simulated)") 58 | 59 | # %% Project 4: Log Sales Summary 60 | # Difficulty: Intermediate 61 | # Description: Write a sales summary with total and count to sales.txt. 62 | # Objective: Practice formatted file writing. 63 | # Tasks: 64 | # - Calculate total and count from sales data and write to sales.txt. 65 | # - Print confirmation or handle errors. 66 | # Expected Output: Sales summary written to sales.txt 67 | sales = [1999.98, 49.99] 68 | total = sum(sales) 69 | count = len(sales) 70 | try: 71 | with open("sales.txt", "w") as file: 72 | file.write(f"Sales Summary\nTotal: ${total:.2f}\nCount: {count}\n") 73 | print("Sales summary written to sales.txt") 74 | except PermissionError: 75 | print("Error: Permission denied (simulated)") 76 | 77 | # %% Project 5: Conditional Order Backup 78 | # Difficulty: Advanced 79 | # Description: Write high-value orders (> $500) to backup.txt. 80 | # Objective: Practice conditional file writing. 81 | # Tasks: 82 | # - Filter orders by value and write to backup.txt. 83 | # - Print confirmation or handle errors. 84 | # Expected Output: High-value orders written to backup.txt 85 | orders = [ 86 | {"order_id": 101, "total": 1999.98}, 87 | {"order_id": 102, "total": 49.99} 88 | ] 89 | try: 90 | with open("backup.txt", "w") as file: 91 | for order in orders: 92 | if order["total"] > 500: 93 | file.write(f"Order {order['order_id']},${order['total']:.2f}\n") 94 | print("High-value orders written to backup.txt") 95 | except PermissionError: 96 | print("Error: Permission denied (simulated)") -------------------------------------------------------------------------------- /Core Python Foundations/08 File Handling/03 CSV Files/CSV Files.py: -------------------------------------------------------------------------------- 1 | # %% Purpose 2 | # Python File Handling: CSV Files 3 | # Purpose: CSV (Comma-Separated Values) files store tabular data, ideal for retail datasets. 4 | # Key Features: Read/write CSV files using csv module. 5 | 6 | # %% 1. Reading a CSV File 7 | # Explanation: Use csv.reader to read rows as lists. 8 | # Example: 9 | import csv 10 | 11 | try: 12 | with open("products.csv", "r") as file: 13 | reader = csv.reader(file) 14 | header = next(reader) # Skip header 15 | products = [(row[0], float(row[1])) for row in reader] 16 | for name, price in products: 17 | print(f"Product: {name}, Price: ${price:.2f}") 18 | except FileNotFoundError: 19 | print("Simulated products.csv:\nProduct: Laptop, Price: $999.99\nProduct: Smartphone, Price: $699.99") 20 | # Output (if file exists): Product: (name), Price: $(price) 21 | # Output (if file missing): Simulated products.csv: Product: Laptop, Price: $999.99 Product: Smartphone, Price: $699.99 22 | # Assumed file content: name,price Laptop,999.99 Smartphone,699.99 23 | 24 | # %% 2. Writing a CSV File 25 | # Explanation: Use csv.writer to write rows. 26 | # Example: 27 | import csv 28 | 29 | products = [ 30 | ["Laptop", 999.99], 31 | ["Smartphone", 699.99] 32 | ] 33 | try: 34 | with open("products_output.csv", "w", newline="") as file: 35 | writer = csv.writer(file) 36 | writer.writerow(["name", "price"]) # Write header 37 | writer.writerows(products) 38 | print("Written to products_output.csv") 39 | except PermissionError: 40 | print("Error: Permission denied (simulated)") 41 | # Output: Written to products_output.csv 42 | # File content: name,price Laptop,999.99 Smartphone,699.99 43 | 44 | # %% 3. Retail Scenario with CSV 45 | # Explanation: Process retail orders in CSV format. 46 | # Example: 47 | import csv 48 | 49 | orders = [ 50 | {"order_id": 101, "total": 1999.98, "date": "2025-04-19"}, 51 | {"order_id": 102, "total": 49.99, "date": "2025-04-20"} 52 | ] 53 | try: 54 | with open("orders.csv", "w", newline="") as file: 55 | writer = csv.writer(file) 56 | writer.writerow(["order_id", "total", "date"]) 57 | for order in orders: 58 | writer.writerow([order["order_id"], order["total"], order["date"]]) 59 | print("Orders written to orders.csv") 60 | # Read back for verification 61 | with open("orders.csv", "r") as file: 62 | reader = csv.DictReader(file) 63 | for row in reader: 64 | print(f"Order {row['order_id']}: ${float(row['total']):.2f}") 65 | except (FileNotFoundError, PermissionError): 66 | print("Simulated orders:\nOrder 101: $1999.98\nOrder 102: $49.99") 67 | # Output: Orders written to orders.csv 68 | # Order 101: $1999.98 Order 102: $49.99 (or simulated output) 69 | 70 | # %% Notes 71 | # Notes: 72 | # - csv module handles delimiters, quotes, and escaping automatically. 73 | # - Use DictReader/DictWriter for header-based access in ML (e.g., datasets) or web apps (e.g., reports). 74 | # - Set newline="" in open() for consistent CSV writing across platforms. -------------------------------------------------------------------------------- /Core Python Foundations/08 File Handling/03 CSV Files/csv_files_projects.py: -------------------------------------------------------------------------------- 1 | # CSV Files Projects 2 | # Purpose: Apply CSV file handling through 5 retail-themed projects. 3 | # Structure: Each project is separated by %% and includes description, tasks, and solution code. 4 | # Note: Solutions use simulated inputs for reproducibility and match the updated base file outputs. 5 | 6 | # %% Project 1: Read Customer Names 7 | # Difficulty: Basic 8 | # Description: Read customers.csv and print customer names. 9 | # Objective: Practice basic CSV reading. 10 | # Tasks: 11 | # - Use csv.reader to read customers.csv and extract names. 12 | # - Print names or simulate if missing. 13 | # Expected Output: Customers: ['Alice', 'Bob'] 14 | import csv 15 | 16 | file_path = "customers.csv" 17 | try: 18 | with open(file_path, "r") as file: 19 | reader = csv.reader(file) 20 | next(reader) # Skip header 21 | names = [row[0] for row in reader] 22 | print(f"Customers: {names}") 23 | except FileNotFoundError: 24 | print("Customers: ['Alice', 'Bob']") 25 | 26 | # %% Project 2: Write Product CSV 27 | # Difficulty: Basic 28 | # Description: Write a list of products to products.csv. 29 | # Objective: Practice basic CSV writing. 30 | # Tasks: 31 | # - Use csv.writer to write products with headers to products.csv. 32 | # - Print confirmation or handle errors. 33 | # Expected Output: Products written to products.csv 34 | import csv 35 | 36 | products = [["Mouse", 29.99], ["Keyboard", 59.99]] 37 | try: 38 | with open("products.csv", "w", newline="") as file: 39 | writer = csv.writer(file) 40 | writer.writerow(["name", "price"]) 41 | writer.writerows(products) 42 | print("Products written to products.csv") 43 | except PermissionError: 44 | print("Error: Permission denied (simulated)") 45 | 46 | # %% Project 3: Calculate Order Total 47 | # Difficulty: Intermediate 48 | # Description: Read orders.csv and calculate the total order value. 49 | # Objective: Practice processing CSV data. 50 | # Tasks: 51 | # - Use csv.DictReader to read orders.csv and sum totals. 52 | # - Print the total or simulate if missing. 53 | # Expected Output: Total order value: $2049.97 54 | import csv 55 | 56 | file_path = "orders.csv" 57 | try: 58 | with open(file_path, "r") as file: 59 | reader = csv.DictReader(file) 60 | total = sum(float(row["total"]) for row in reader) 61 | print(f"Total order value: ${total:.2f}") 62 | except FileNotFoundError: 63 | print("Total order value: $2049.97") 64 | 65 | # %% Project 4: Filter High-Value Orders 66 | # Difficulty: Intermediate 67 | # Description: Read orders.csv and list orders with total > $500. 68 | # Objective: Practice filtering CSV data. 69 | # Tasks: 70 | # - Use csv.DictReader to read orders.csv and filter by total. 71 | # - Print order IDs or simulate if missing. 72 | # Expected Output: High-value orders: [101] 73 | import csv 74 | 75 | file_path = "orders.csv" 76 | high_value_orders = [] 77 | try: 78 | with open(file_path, "r") as file: 79 | reader = csv.DictReader(file) 80 | for row in reader: 81 | if float(row["total"]) > 500: 82 | high_value_orders.append(int(row["order_id"])) 83 | print(f"High-value orders: {high_value_orders}") 84 | except FileNotFoundError: 85 | print("High-value orders: [101]") 86 | 87 | # %% Project 5: Comprehensive CSV Processor 88 | # Difficulty: Advanced 89 | # Description: Read products.csv, add discounts, and write to discounted_products.csv. 90 | # Objective: Practice reading and writing CSV with processing. 91 | # Tasks: 92 | # - Read products.csv, apply a 10% discount, and write to a new CSV. 93 | # - Print confirmation or simulate if missing. 94 | # Expected Output: Discounted products written to discounted_products.csv 95 | import csv 96 | 97 | input_file = "products.csv" 98 | output_file = "discounted_products.csv" 99 | try: 100 | with open(input_file, "r") as file: 101 | reader = csv.reader(file) 102 | header = next(reader) 103 | products = [[row[0], float(row[1]) * 0.9] for row in reader] 104 | with open(output_file, "w", newline="") as file: 105 | writer = csv.writer(file) 106 | writer.writerow(["name", "price"]) 107 | writer.writerows(products) 108 | print("Discounted products written to discounted_products.csv") 109 | except FileNotFoundError: 110 | print("Discounted products written to discounted_products.csv (simulated)") 111 | except PermissionError: 112 | print("Error: Permission denied (simulated)") -------------------------------------------------------------------------------- /Core Python Foundations/09 Iterators and Generators/01 Iterators/Iterators.py: -------------------------------------------------------------------------------- 1 | # %% Purpose 2 | # Python Iterators and Generators: Iterators 3 | # Purpose: Iterators allow sequential access to elements in a collection, implementing __iter__() and __next__(). 4 | # Key Features: Memory-efficient iteration, supports for loops, custom iteration logic. 5 | 6 | # %% 1. Using Built-in Iterators 7 | # Explanation: Lists, tuples, etc., are iterable; use iter() and next() for manual iteration. 8 | # Example: 9 | products = ["Laptop", "Smartphone", "Coffee Maker"] 10 | iterator = iter(products) 11 | print("First product:", next(iterator)) 12 | print("Second product:", next(iterator)) 13 | # Output: First product: Laptop 14 | # Second product: Smartphone 15 | 16 | # %% 2. Creating a Custom Iterator 17 | # Explanation: Define a class with __iter__() and __next__() methods. 18 | # Example: 19 | class ProductInventory: 20 | def __init__(self, products): 21 | self.products = products 22 | self.index = 0 23 | def __iter__(self): 24 | return self 25 | def __next__(self): 26 | if self.index < len(self.products): 27 | product = self.products[self.index] 28 | self.index += 1 29 | return product 30 | raise StopIteration 31 | 32 | inventory = ProductInventory(["Mouse", "Keyboard", "Monitor"]) 33 | for product in inventory: 34 | print(f"Inventory item: {product}") 35 | # Output: Inventory item: Mouse 36 | # Inventory item: Keyboard 37 | # Inventory item: Monitor 38 | 39 | # %% 3. Retail Scenario with Iterators 40 | # Explanation: Iterate over retail orders with custom logic (e.g., filter expensive orders). 41 | # Example: 42 | class OrderIterator: 43 | def __init__(self, orders): 44 | self.orders = orders 45 | self.index = 0 46 | def __iter__(self): 47 | return self 48 | def __next__(self): 49 | while self.index < len(self.orders): 50 | order = self.orders[self.index] 51 | self.index += 1 52 | if order["total"] > 500: # Only return expensive orders 53 | return order 54 | raise StopIteration 55 | 56 | orders = [ 57 | {"order_id": 101, "total": 1999.98}, 58 | {"order_id": 102, "total": 49.99}, 59 | {"order_id": 103, "total": 699.99} 60 | ] 61 | expensive_orders = OrderIterator(orders) 62 | for order in expensive_orders: 63 | print(f"Expensive order {order['order_id']}: ${order['total']:.2f}") 64 | # Output: Expensive order 101: $1999.98 65 | # Expensive order 103: $699.99 66 | 67 | # %% Notes 68 | # Notes: 69 | # - Iterators are memory-efficient for large datasets in ML (e.g., batch processing) or web apps (e.g., streaming API responses). 70 | # - StopIteration signals the end of iteration; handle in custom iterators. 71 | # - All iterables (e.g., lists) can be converted to iterators using iter(). -------------------------------------------------------------------------------- /Core Python Foundations/09 Iterators and Generators/02 Generators/Generators.py: -------------------------------------------------------------------------------- 1 | # %% Purpose 2 | # Python Iterators and Generators: Generators 3 | # Purpose: Generators are iterators created with functions using 'yield', producing values lazily. 4 | # Key Features: Memory-efficient, simplifies iterator creation, one-time iteration. 5 | 6 | # %% 1. Basic Generator Function 7 | # Explanation: Use 'yield' to produce values one at a time. 8 | # Example: 9 | def product_generator(products): 10 | for product in products: 11 | yield product 12 | 13 | products = ["Laptop", "Smartphone", "Coffee Maker"] 14 | gen = product_generator(products) 15 | print("First product:", next(gen)) 16 | print("Second product:", next(gen)) 17 | # Output: First product: Laptop 18 | # Second product: Smartphone 19 | 20 | # %% 2. Generator with Logic 21 | # Explanation: Include logic to filter or transform values. 22 | # Example: 23 | def discount_generator(prices, discount_rate): 24 | for price in prices: 25 | yield price * (1 - discount_rate) 26 | 27 | prices = [999.99, 699.99, 49.99] 28 | discounted_prices = discount_generator(prices, 0.1) 29 | for price in discounted_prices: 30 | print(f"Discounted price: ${price:.2f}") 31 | # Output: Discounted price: $899.99 32 | # Discounted price: $629.99 33 | # Discounted price: $44.99 34 | 35 | # %% 3. Retail Scenario with Generators 36 | # Explanation: Generate retail order IDs incrementally. 37 | # Example: 38 | def order_id_generator(start_id, count): 39 | for i in range(count): 40 | yield start_id + i 41 | 42 | order_ids = order_id_generator(1001, 3) 43 | orders = [{"order_id": order_id, "total": 1000.00} for order_id in order_ids] 44 | for order in orders: 45 | print(f"Order {order['order_id']}: ${order['total']:.2f}") 46 | # Output: Order 1001: $1000.00 47 | # Order 1002: $1000.00 48 | # Order 1003: $1000.00 49 | 50 | # %% Notes 51 | # Notes: 52 | # - Generators are ideal for large datasets in ML (e.g., streaming data) or web apps (e.g., lazy API responses). 53 | # - Generators can only be iterated once; store results in a list if needed. 54 | # - Use 'yield' to pause and resume function execution. -------------------------------------------------------------------------------- /Core Python Foundations/09 Iterators and Generators/03 Yield Statement/Yield Statement.py: -------------------------------------------------------------------------------- 1 | # %% Purpose 2 | # Python Iterators and Generators: Yield Statement 3 | # Purpose: The 'yield' statement produces values in generators, pausing function execution. 4 | # Key Features: Lazy evaluation, state preservation, enables generator functions. 5 | 6 | # %% 1. Basic Yield Usage 7 | # Explanation: 'yield' returns a value and pauses the function, resuming on next call. 8 | # Example: 9 | def product_yielder(): 10 | yield "Laptop" 11 | yield "Smartphone" 12 | yield "Coffee Maker" 13 | 14 | gen = product_yielder() 15 | print("First yield:", next(gen)) 16 | print("Second yield:", next(gen)) 17 | # Output: First yield: Laptop 18 | # Second yield: Smartphone 19 | 20 | # %% 2. Yield with Dynamic Data 21 | # Explanation: Use 'yield' in loops to generate values dynamically. 22 | # Example: 23 | def price_incrementer(start_price, step, count): 24 | current_price = start_price 25 | for _ in range(count): 26 | yield current_price 27 | current_price += step 28 | 29 | prices = price_incrementer(100.00, 10.00, 4) 30 | for price in prices: 31 | print(f"Price: ${price:.2f}") 32 | # Output: Price: $100.00 33 | # Price: $110.00 34 | # Price: $120.00 35 | # Price: $130.00 36 | 37 | # %% 3. Retail Scenario with Yield 38 | # Explanation: Generate stock alerts for low inventory using 'yield'. 39 | # Example: 40 | def stock_alert(products): 41 | for product in products: 42 | if product["stock"] < 50: 43 | yield f"Low stock alert: {product['name']} ({product['stock']} units)" 44 | 45 | inventory = [ 46 | {"name": "Mouse", "stock": 30}, 47 | {"name": "Keyboard", "stock": 60}, 48 | {"name": "Monitor", "stock": 20} 49 | ] 50 | alerts = stock_alert(inventory) 51 | for alert in alerts: 52 | print(alert) 53 | # Output: Low stock alert: Mouse (30 units) 54 | # Low stock alert: Monitor (20 units) 55 | 56 | # %% Notes 57 | # Notes: 58 | # - 'yield' enables lazy evaluation, ideal for ML (e.g., batch processing) or web apps (e.g., streaming data). 59 | # - Functions with 'yield' become generators; they maintain state between calls. 60 | # - Combine with try-except to handle StopIteration for robustness. -------------------------------------------------------------------------------- /Core Python Foundations/10 Decorators/01 Function Decorators/Function Decorators.py: -------------------------------------------------------------------------------- 1 | # %% Purpose 2 | # Python Decorators: Function Decorators 3 | # Purpose: Function decorators wrap functions to add functionality (e.g., logging, timing) without modifying their code. 4 | # Key Features: Reusability, separation of concerns, use of @ syntax. 5 | 6 | # %% 1. Basic Function Decorator 7 | # Explanation: A decorator is a function that takes another function and extends its behavior. 8 | # Example: 9 | def logging_decorator(func): 10 | def wrapper(*args, **kwargs): 11 | print(f"Calling {func.__name__} with args: {args}, kwargs: {kwargs}") 12 | result = func(*args, **kwargs) 13 | print(f"{func.__name__} returned: {result}") 14 | return result 15 | return wrapper 16 | 17 | @logging_decorator 18 | def calculate_total(price, quantity): 19 | return price * quantity 20 | 21 | total = calculate_total(999.99, 2) 22 | # Output: Calling calculate_total with args: (999.99, 2), kwargs: {} 23 | # calculate_total returned: 1999.98 24 | 25 | # %% 2. Decorator with Arguments 26 | # Explanation: Use a decorator factory to pass arguments to the decorator. 27 | # Example: 28 | def discount_decorator(discount_rate): 29 | def decorator(func): 30 | def wrapper(*args, **kwargs): 31 | original_price = func(*args, **kwargs) 32 | discounted_price = original_price * (1 - discount_rate) 33 | return discounted_price 34 | return wrapper 35 | return decorator 36 | 37 | @discount_decorator(0.1) # 10% discount 38 | def calculate_order_total(items): 39 | return sum(items) 40 | 41 | order_total = calculate_order_total([999.99, 699.99]) 42 | print(f"Discounted order total: ${order_total:.2f}") 43 | # Output: Discounted order total: $1499.98 44 | 45 | # %% 3. Retail Scenario with Function Decorator 46 | # Explanation: Use a decorator to log retail order processing time. 47 | # Example: 48 | import time 49 | 50 | def timing_decorator(func): 51 | def wrapper(*args, **kwargs): 52 | start_time = time.time() 53 | result = func(*args, **kwargs) 54 | end_time = time.time() 55 | print(f"{func.__name__} took {end_time - start_time:.2f} seconds") 56 | return result 57 | return wrapper 58 | 59 | @timing_decorator 60 | def process_orders(orders): 61 | # Simulate processing 62 | for order in orders: 63 | time.sleep(0.1) # Simulate work 64 | return len(orders) 65 | 66 | orders = [{"order_id": 101, "total": 1999.98}, {"order_id": 102, "total": 49.99}] 67 | processed = process_orders(orders) 68 | print(f"Processed {processed} orders") 69 | # Output: process_orders took 0.20 seconds (approx) 70 | # Processed 2 orders 71 | 72 | # %% Notes 73 | # Notes: 74 | # - Function decorators are used in ML for logging model training or web apps for authentication. 75 | # - Use *args and **kwargs in wrappers to handle any function signature. 76 | # - Stack multiple decorators (@dec1 @dec2) for combined functionality. -------------------------------------------------------------------------------- /Core Python Foundations/10 Decorators/02 Class Decorators/Class Decorators.py: -------------------------------------------------------------------------------- 1 | # %% Purpose 2 | # Python Decorators: Class Decorators 3 | # Purpose: Class decorators modify or enhance class definitions, often for adding methods or validation. 4 | # Key Features: Metaprogramming, class-level functionality, reusable class modifications. 5 | 6 | # %% 1. Basic Class Decorator 7 | # Explanation: A class decorator is a function that takes a class and returns a modified class. 8 | # Example: 9 | def add_display_method(cls): 10 | def display(self): 11 | return f"{self.__class__.__name__}: {vars(self)}" 12 | cls.display = display 13 | return cls 14 | 15 | @add_display_method 16 | class Product: 17 | def __init__(self, name, price): 18 | self.name = name 19 | self.price = price 20 | 21 | product = Product("Laptop", 999.99) 22 | print(product.display()) 23 | # Output: Product: {'name': 'Laptop', 'price': 999.99} 24 | 25 | # %% 2. Class Decorator with Arguments 26 | # Explanation: Use a decorator factory to pass arguments to the class decorator. 27 | # Example: 28 | def add_discount(discount_rate): 29 | def decorator(cls): 30 | original_init = cls.__init__ 31 | def new_init(self, *args, **kwargs): 32 | original_init(self, *args, **kwargs) 33 | self.discounted_price = self.price * (1 - discount_rate) 34 | cls.__init__ = new_init 35 | return cls 36 | return decorator 37 | 38 | @add_discount(0.1) # 10% discount 39 | class Order: 40 | def __init__(self, order_id, price): 41 | self.order_id = order_id 42 | self.price = price 43 | 44 | order = Order(101, 999.99) 45 | print(f"Order {order.order_id}: Original ${order.price:.2f}, Discounted ${order.discounted_price:.2f}") 46 | # Output: Order 101: Original $999.99, Discounted $899.99 47 | 48 | # %% 3. Retail Scenario with Class Decorator 49 | # Explanation: Use a class decorator to add validation for retail product attributes. 50 | # Example: 51 | def validate_positive_attributes(cls): 52 | original_init = cls.__init__ 53 | def new_init(self, *args, **kwargs): 54 | original_init(self, *args, **kwargs) 55 | for attr, value in vars(self).items(): 56 | if isinstance(value, (int, float)) and value < 0: 57 | raise ValueError(f"{attr} must be non-negative") 58 | cls.__init__ = new_init 59 | return cls 60 | 61 | @validate_positive_attributes 62 | class InventoryItem: 63 | def __init__(self, name, stock, price): 64 | self.name = name 65 | self.stock = stock 66 | self.price = price 67 | 68 | item = InventoryItem("Mouse", 30, 29.99) 69 | print(f"Item: {item.name}, Stock: {item.stock}, Price: ${item.price:.2f}") 70 | # Output: Item: Mouse, Stock: 30, Price: $29.99 71 | # Note: Try InventoryItem("Mouse", -30, 29.99) to see ValueError 72 | 73 | # %% Notes 74 | # Notes: 75 | # - Class decorators are useful in ML for model validation or web apps for ORM enhancements. 76 | # - Preserve original methods (e.g., __init__) to avoid breaking functionality. 77 | # - Use for metaprogramming tasks like adding methods or enforcing invariants. -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2025 rohanmistry231 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. -------------------------------------------------------------------------------- /Python Coding Practice Questions/README.md: -------------------------------------------------------------------------------- 1 | # 100+ Python Coding Interview Questions from Basic to Advanced 🚀 2 | 3 | **Master Python, Ace Interviews!** Dive into **102 meticulously crafted Python coding exercises** designed to prepare you for technical interviews at top tech companies like Google, Amazon, and Microsoft. From **beginner-friendly basics** to **mind-bending advanced algorithms**, this repository has it all! 📚💡 Retail-themed examples (e.g., order processing, inventory management) bring real-world flavor to your learning journey. Ready to crush your next interview? Let’s get coding! 🔥 4 | 5 | [![Python Version](https://img.shields.io/badge/Python-3.x-blue)](https://www.python.org/) [![Exercises](https://img.shields.io/badge/Exercises-102-green)](./) [![Topics](https://img.shields.io/badge/Topics-Algorithms%20|%20Data%20Structures-orange)](./) 6 | 7 | ## 🎯 Why This Repository? 8 | 9 | This collection of **100+ Python coding questions** spans **three skill levels**—Basic, Intermediate, and Advanced—with **34 exercises each**, totaling **102 challenges**. Each exercise is crafted to mirror real interview problems, complete with: 10 | - **Clear Problem Statement**: Understand the task at a glance. 11 | - **Practical Example**: See inputs and outputs for context. 12 | - **Hidden Solution**: Code and explanation tucked in a collapsible `
` section—solve first, then check! 🙌 13 | 14 | Inspired by top resources like [GeeksforGeeks](https://www.geeksforgeeks.org/python-interview-questions/), [LeetCode](https://leetcode.com/), and [InterviewBit](https://www.interviewbit.com/python-interview-questions/), these exercises cover **syntax, data structures, algorithms**, and **advanced Python concepts** to ensure you’re interview-ready. 15 | 16 | ## 🗂️ Explore the Exercises 17 | 18 | Navigate to the folder that matches your skill level: 19 | 20 | | Folder | Description | Exercises | Link | 21 | |--------|-------------|-----------|------| 22 | | **Basic** | Kickstart your journey with beginner-friendly exercises on loops, conditionals, strings, and lists. Perfect for new coders or those brushing up on fundamentals. | 34 | [Basic Exercises](./Basic/README.md) | 23 | | **Intermediate** | Level up with challenges on dictionaries, sets, sorting algorithms, decorators, and generators. Ideal for developers ready to tackle mid-tier interview questions. | 34 | [Intermediate Exercises](./Intermediate/README.md) | 24 | | **Advanced** | Conquer complex algorithms (e.g., dynamic programming, graph algorithms) and advanced Python features (e.g., metaclasses, multiprocessing). For pros aiming for top-tier roles. | 34 | [Advanced Exercises](./Advanced/README.md) | 25 | 26 | ## 🚀 Get Started in 3 Steps 27 | 28 | 1. **Clone or Download**: 29 | ```bash 30 | git clone https://github.com/rohanmistry231/Python-Interview-Preparation.git 31 | ``` 32 | Or grab the ZIP file from the repository. 33 | 34 | 2. **Pick Your Level**: 35 | - Open the `Basic`, `Intermediate`, or `Advanced` folder. 36 | - Each contains a single `.md` file packed with 34 exercises. 37 | 38 | 3. **Practice Like a Pro**: 39 | - Open the markdown file in a viewer (e.g., GitHub, VS Code). 40 | - Read the problem and example, write your solution, then click "Click to expand solution" to compare and learn. 41 | - **Pro Tip**: Start with Basic, graduate to Intermediate, and tackle Advanced to become an interview rockstar! 🌟 42 | 43 | **Want all 102 exercises in one file?** Merge them with: 44 | ```bash 45 | cat Basic/README.md Intermediate/README.md Advanced/README.md > all_python_exercises.md 46 | ``` 47 | 48 | ## 🌟 What Makes This Special? 49 | 50 | - **100+ Challenges**: 102 exercises (34 Basic + 34 Intermediate + 34 Advanced) covering every angle of Python interviews. 51 | - **Interview-Focused**: Problems mirror questions asked at FAANG and other top companies. 52 | - **Interactive Learning**: Hidden solutions encourage you to think before peeking. 53 | - **Retail Scenarios**: Solve real-world problems like order scheduling and stock updates. 54 | - **Progressive Path**: Build skills step-by-step from beginner to expert. 55 | 56 | ## 🛠️ Prerequisites 57 | 58 | - **Python 3.x**: Install Python to test your code ([Download Python](https://www.python.org/downloads/)). 59 | - **Editor/IDE**: Use VS Code, PyCharm, or any editor you love. 60 | - **Markdown Viewer**: View `.md` files in GitHub, VS Code, or any markdown-compatible tool. 61 | - **Optional Libraries**: Advanced exercise #32 (Bloom Filter) needs `mmh3` and `bitarray`: 62 | ```bash 63 | pip install mmh3 bitarray 64 | ``` 65 | 66 | ## 🤝 Contribute & Shine 67 | 68 | Got a killer exercise or improvement idea? We’d love your input! 💡 69 | 70 | 1. Fork this repository. 71 | 2. Add or tweak exercises in the relevant `.md` file, keeping the format: 72 | - Problem statement 73 | - Example 74 | - Solution in `
` with code and explanation 75 | 3. Submit a pull request with a clear description. 76 | 77 | ## 🙌 Acknowledgments 78 | 79 | - **Inspiration**: [GeeksforGeeks](https://www.geeksforgeeks.org/python-interview-questions/), [LeetCode](https://leetcode.com/), [InterviewBit](https://www.interviewbit.com/python-interview-questions/). 80 | - **Python Community**: Thanks for the wealth of knowledge and problem sets. 81 | 82 | --- 83 | 84 | **Ready to conquer your Python interviews?** Jump into these 100+ coding challenges and level up your skills! 💪 Have feedback or questions? Open an issue or reach out. Happy coding, and best of luck crushing those interviews! 🎉 -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # 🐍 Python Interview Preparation 2 | 3 |
4 | Python Logo 5 | NumPy 6 | Pandas 7 | scikit-learn 8 | Matplotlib 9 | Seaborn 10 | 11 |
12 |

Your comprehensive guide to mastering Python for AI/ML interviews

13 | 14 | --- 15 | 16 | ## 📖 Introduction 17 | 18 | Welcome to my Python prep for AI/ML interviews! 🚀 This repository is your essential guide for mastering Python, the backbone of AI and data science, with hands-on coding and interview-focused practice. From core fundamentals to advanced techniques, it’s crafted to help you shine in technical interviews and AI projects with clarity and confidence. 19 | 20 | ## 🌟 What’s Inside? 21 | 22 | - **Core Python Mastery**: Dive deep into data structures, control flow, OOP, and more to ace coding tests. 23 | - **AI/ML Libraries**: Explore NumPy, Pandas, Matplotlib, Scikit-learn, and other key toolkits. 24 | - **Hands-on Practice**: Solve curated coding problems with detailed solutions to sharpen your edge. 25 | - **Interview Question Bank**: Tackle common questions with clear, concise answers. 26 | - **Performance Optimization**: Learn tips for writing efficient, interview-ready Python code. 27 | 28 | ## 🔍 Who Is This For? 29 | 30 | - Data Scientists prepping for technical interviews. 31 | - Machine Learning Engineers strengthening Python foundations. 32 | - AI Researchers enhancing coding efficiency. 33 | - Software Engineers transitioning to AI/ML roles. 34 | - Anyone mastering Python for data-centric applications. 35 | 36 | ## 🗺️ Comprehensive Learning Roadmap 37 | 38 | --- 39 | 40 | ### 🏗️ Core Python Foundations 41 | 42 | #### 📊 Data Structures 43 | - Lists 44 | - Dictionaries 45 | - Tuples 46 | - Sets 47 | - Strings 48 | - Frozen Sets 49 | 50 | #### 🔄 Control Flow 51 | - If-Else Statements 52 | - Elif Statements 53 | - Nested Conditionals 54 | - For Loops 55 | - While Loops 56 | - Break Statement 57 | - Continue Statement 58 | - Pass Statement 59 | 60 | #### 🧩 Functions 61 | - Defining Functions 62 | - Positional Arguments 63 | - Keyword Arguments 64 | - Default Parameters 65 | - Variable-Length Arguments (*args, **kwargs) 66 | - Lambda Expressions 67 | - Recursion 68 | - Function Annotations 69 | 70 | #### 🔍 Comprehensions 71 | - List Comprehensions 72 | - Dictionary Comprehensions 73 | - Set Comprehensions 74 | - Generator Expressions 75 | 76 | #### ⚠️ Exception Handling 77 | - Try-Except 78 | - Multiple Except Blocks 79 | - Else Clause 80 | - Finally Clause 81 | - Raise Statement 82 | - Custom Exceptions 83 | 84 | #### 🧬 Object-Oriented Programming 85 | - Classes and Objects 86 | - Attributes 87 | - Methods 88 | - Inheritance 89 | - Multiple Inheritance 90 | - Encapsulation 91 | - Polymorphism 92 | - Abstract Classes 93 | - Static Methods 94 | - Class Methods 95 | 96 | #### 📦 Modules and Packages 97 | - Importing Modules 98 | - Creating Modules 99 | - Packages 100 | - Standard Library 101 | - math 102 | - random 103 | - datetime 104 | - os 105 | - sys 106 | - time 107 | 108 | #### 📄 File Handling 109 | - Reading Files 110 | - Writing Files 111 | - CSV Files 112 | 113 | #### 🔄 Iterators and Generators 114 | - Iterators 115 | - Generators 116 | - Yield Statement 117 | 118 | #### 🎁 Decorators 119 | - Function Decorators 120 | - Class Decorators 121 | 122 | --- 123 | 124 | ## 💡 Why Master Python for AI/ML? 125 | 126 | Python is the go-to language for AI/ML, and here’s why: 127 | 1. **Versatility**: Powers the full AI workflow—from data cleaning to deployment. 128 | 2. **Rich Ecosystem**: Packed with libraries like NumPy and Scikit-learn. 129 | 3. **Readability**: Clean syntax boosts focus on problem-solving. 130 | 4. **Industry Demand**: A must-have skill for 6 LPA+ AI/ML roles. 131 | 5. **Community Support**: Tap into a huge network of experts. 132 | 133 | This repo is my roadmap to mastering Python for technical interviews and AI/ML careers—let’s build that skill set together! 134 | 135 | ## 📆 Study Plan 136 | 137 | - **Week 1-2**: Core Python Fundamentals 138 | - **Week 3-4**: Data Structures and Algorithms 139 | 140 | ## 🤝 Contributions 141 | 142 | Love to collaborate? Here’s how! 🌟 143 | 1. Fork the repository. 144 | 2. Create a feature branch (`git checkout -b feature/amazing-addition`). 145 | 3. Commit your changes (`git commit -m 'Add some amazing content'`). 146 | 4. Push to the branch (`git push origin feature/amazing-addition`). 147 | 5. Open a Pull Request. 148 | 149 | --- 150 | 151 |
152 |

Happy Learning and Good Luck with Your Interviews! ✨

153 |
154 | --------------------------------------------------------------------------------