Python Basics Variables and Data Types Assignment: x = 10 , name = "Alice" Integers: age = 30 Floats: price = 19.99 Strings: message = "Hello, Python!" Booleans: is_active = True Lists: Ordered, mutable. my_list = [1, 2, 'a'] Tuples: Ordered, immutable. my_tuple = (1, 2, 'a') Dictionaries: Unordered, key-value pairs. my_dict = {'name': 'Bob', 'age': 25} Sets: Unordered, unique elements. my_set = {1, 2, 3} Operators Arithmetic: + , - , * , / , % (modulo), ** (exponent), // (floor division) Comparison: == , != , , > , , >= Logical: and , or , not Assignment: = , += , -= , *= , etc. Control Flow If/Elif/Else: if condition1: # code elif condition2: # code else: # code For Loop: for item in iterable: # code While Loop: while condition: # code Keywords: break , continue , pass Functions Definition: def greet(name): return f"Hello, {name}!" Lambda Functions: add = lambda x, y: x + y Arguments: Positional, Keyword ( func(a=1, b=2) ), Default ( func(x=0) ), Arbitrary Positional ( *args ), Arbitrary Keyword ( **kwargs ) Intermediate Python String Formatting f-strings (Python 3.6+): f"Name: {name}, Age: {age}" .format(): "Name: {}, Age: {}".format(name, age) Old style (%): "Name: %s, Age: %d" % (name, age) (Discouraged) Data Structures Operations List Comprehensions: squares = [x**2 for x in range(10) if x % 2 == 0] Dictionary Comprehensions: {k: v for k, v in my_dict.items() if v > 0} Tuple Unpacking: a, b, c = my_tuple Set Operations: union() , intersection() , difference() Error Handling Try-Except: try: # code that might raise an error except ValueError as e: print(f"Error: {e}") except Exception: # general error finally: # always executed File I/O Reading: with open('file.txt', 'r') as f: content = f.read() lines = f.readlines() Writing: with open('output.txt', 'w') as f: f.write("Hello, world!") Appending: Use 'a' mode. Classes and Objects (OOP) Class Definition: class MyClass: def __init__(self, value): self.value = value def get_value(self): return self.value Inheritance: class Child(Parent): Polymorphism: Methods with the same name in different classes. Encapsulation: Using conventions like _private_var (single underscore) or __mangled_var (double underscore). Decorators: Functions that modify other functions. @property , @staticmethod , @classmethod . Advanced Python Generators and Iterators Generators: Functions that yield values, creating iterators. Memory efficient. def count_up_to(n): i = 0 while i Iterators: Objects implementing __iter__() and __next__() . Decorators Custom Decorator: def my_decorator(func): def wrapper(*args, **kwargs): print("Before function call") result = func(*args, **kwargs) print("After function call") return result return wrapper @my_decorator def say_hello(name): return f"Hello, {name}!" Context Managers Using with statement: Ensures resources are properly acquired/released. from contextlib import contextmanager @contextmanager def managed_resource(name): print(f"Acquiring {name}") yield name print(f"Releasing {name}") with managed_resource("database") as db: print(f"Working with {db}") Asynchronous Programming ( asyncio ) Event Loop: Manages and distributes execution of tasks. Coroutines: Functions defined with async def , executed with await . import asyncio async def fetch_data(delay): await asyncio.sleep(delay) return f"Data after {delay} seconds" async def main(): task1 = asyncio.create_task(fetch_data(2)) task2 = asyncio.create_task(fetch_data(1)) print("Tasks started...") result1 = await task1 result2 = await task2 print(result1) print(result2) if __name__ == "__main__": asyncio.run(main()) Metaclasses Customizing Class Creation: Classes are instances of metaclasses. type is the default metaclass. Example: class MyMeta(type): def __new__(mcs, name, bases, dct): # Modify class dictionary before creation dct['added_attribute'] = 100 return super().__new__(mcs, name, bases, dct) class MyNewClass(metaclass=MyMeta): pass # MyNewClass.added_attribute will be 100 Concurrency and Parallelism threading module: For I/O-bound tasks (due to GIL). multiprocessing module: For CPU-bound tasks (bypasses GIL). GIL (Global Interpreter Lock): Allows only one thread to execute Python bytecode at a time. Python Ecosystem & Best Practices (2025) Package Management pip : Python's package installer. pip install package_name pip install -r requirements.txt pip freeze > requirements.txt Virtual Environments: python -m venv .venv , source .venv/bin/activate (Linux/macOS) or .venv\Scripts\activate (Windows). Poetry/Rye/PDM: Modern dependency management and packaging tools. Testing unittest : Built-in module for unit testing. pytest : Popular third-party testing framework. Assertions: assert x == y Fixtures: Setup/teardown for tests. Common Libraries Data Science: NumPy , Pandas , Matplotlib , SciPy , scikit-learn Web Development: Django , Flask , FastAPI Requests: HTTP client library. SQLAlchemy: ORM for databases. Pydantic: Data validation and settings management. Type Hinting (PEP 484) Basic types: def greet(name: str) -> str: Collections: List[int] , Dict[str, float] (from typing module) Union: Union[str, int] Optional: Optional[str] (equivalent to Union[str, None] ) Type Aliases: Vector = List[float] Newer syntax (Python 3.9+): list[int] , dict[str, float] Structural Pattern Matching (Python 3.10+): match / case statements.