2.1 Functions
Functions are reusable blocks of code that perform a specific task, promoting modularity, code reuse, and abstraction.
Defining Functions
-
Use the
defkeyword followed by the function name and parentheses. -
Naming convention:
snake_case(e.g.,calculate_sum). -
Docstring: A string literal as the first statement, documenting purpose, parameters, and return values. Convention: triple quotes (
"""...""").
Parameters & Arguments
| Type | Description | Example |
|---|---|---|
| Positional | Arguments matched by position. | func(1, 2) |
| Keyword | Arguments matched by parameter name. | func(b=2, a=1) |
| Default Values | Parameters assigned default values if omitted. | def func(a=0): |
*args |
Variable-length positional arguments (tuple). | def func(*args): |
**kwargs |
Variable-length keyword arguments (dict). | def func(**kwargs): |
Return Statement
-
Returns a single value or multiple values (as a tuple).
-
Without
return, function returnsNone.
Scope & Namespaces
-
Local scope: Variables defined inside a function.
-
Global scope: Variables defined at the module level.
-
globalkeyword: Modify a global variable inside a function. -
nonlocalkeyword: Modify a variable in the enclosing (non-global) scope (used in nested functions).
Lambda Functions
-
Anonymous, single-expression functions.
-
Syntax:
lambda arguments: expression -
Commonly used with
map(),filter(),sorted().sorted(list_of_tuples, key=lambda x: x[1])
[!TIP]
Common Pitfall: Mutable default arguments (e.g.,
def func(lst=[])). The default list is shared across calls. UseNoneand initialize inside.
2.2 Fundamental Data Structures
Lists
-
Mutable, ordered sequences.
-
Creation:
[],list(), list comprehensions. -
Indexing/Slicing:
lst[i],lst[i:j](supports negative indices). -
Common Methods & Time Complexity:
| Method | Avg. Time | Description | |--------|-----------|-------------| |
append(x)| $O(1)$ | Add to end. | |insert(i, x)| $O(n)$ | Insert at index. | |pop([i])| $O(1)$ (end), $O(n)$ (middle) | Remove & return. | |remove(x)| $O(n)$ | Remove first occurrence. | |sort()| $O(n \log n)$ | In-place sort. | -
List Comprehensions:
[expr for item in iterable if condition]. Supports nested loops. -
Nested Lists: Lists containing other lists (e.g., matrices).
Tuples
-
Immutable, ordered sequences.
-
Creation:
(),tuple(), packing/unpacking. -
Packing/Unpacking:
a, b = (1, 2)ort = 1, 2. -
Use as dict keys: Only if all elements are immutable.
-
Comparison with lists: Tuples are faster, safer (hashable if immutable), often used for fixed data.
Dictionaries
-
Key-value pairs, keys must be immutable (str, int, tuple).
-
Creation:
{},dict(), dict comprehensions{k: v for k, v in ...}. -
Access:
dict[key],dict.get(key, default). -
Common Methods:
-
keys(),values(),items()return view objects. -
pop(key),popitem()(LIFO),update(),setdefault().
-
-
Iteration:
for k, v in dict.items():.
Sets
-
Unordered, unique elements.
-
Creation:
{}(empty set:set()), set comprehensions{x for x in ...}. -
Operations (set algebra):
| Operation | Symbol | Description | |-----------|--------|-------------| | Union |
\|| Elements in either set. | | Intersection |&| Elements in both. | | Difference |-| In left not right. | | Symmetric Difference |^| In either but not both. | -
Methods:
add(),remove()(error if missing),discard()(no error),pop()(arbitrary),clear().
Comparison of Core Structures
| Feature | List | Tuple | Dict | Set |
|---|---|---|---|---|
| Mutable | Yes | No | Yes (keys immutable) | Yes |
| Ordered | Yes | Yes | No (Py3.7+ insertion order) | No |
| Syntax | [] |
() |
{} |
{} (or set()) |
| Duplicates | Allowed | Allowed | Keys unique | Not allowed |
| Primary Use | Sequence | Fixed sequence | Mapping | Unique collection |
[!TIP]
Time Complexity: Dict and set operations (lookup, insert, delete) average $O(1)$ due to hashing. List search is $O(n)$.
2.3 Modules and Packages
Concept
-
Module: A single
.pyfile containing Python definitions (functions, classes, variables). -
Package: A directory containing multiple modules and a special
__init__.pyfile (can be empty), enabling hierarchical organization.
Importing Modules
| Statement | Effect |
|---|---|
import module |
Imports entire module; access via module.name. |
from module import name |
Imports specific names directly. |
from module import * |
Imports all public names (discouraged; causes namespace pollution). |
import module as alias |
Renames module for convenience. |
Standard Library Highlights
-
math: Mathematical functions (sqrt,sin). -
random: Random number generation (randint,choice). -
datetime: Date/time manipulation (datetime.now()). -
os: OS interactions (path,listdir). -
sys: System-specific parameters (argv,exit).
Creating Your Own Modules
-
Write a
.pyfile (e.g.,mymodule.py). -
Import in another script:
import mymoduleorfrom mymodule import myfunc.
The __name__ == "__main__" Guard
-
Purpose: Code inside this block runs only when the file is executed directly (not when imported).
-
Pattern:
if __name__ == "__main__": # test code or script execution
Packages
-
Directory structure:
package/ ├── __init__.py ├── module1.py └── subpackage/ ├── __init__.py └── module2.py -
Import:
from package.subpackage import module2.
2.4 File Input/Output (I/O)
File Paths
-
Absolute path: Full path from root (e.g.,
C:\data\file.txtor/home/user/file.txt). -
Relative path: Path relative to current working directory (e.g.,
data/file.txt).
Opening Files
-
Function:
open(file, mode, encoding=None). -
Common Modes:
| Mode | Description | |------|-------------| |
'r'| Read (default). | |'w'| Write (truncates existing). | |'a'| Append. | |'x'| Exclusive creation (fails if exists). | |'b'| Binary mode. | |'t'| Text mode (default). | |'+'| Update (read + write). | -
Example:
open('data.txt', 'r', encoding='utf-8').
Reading Files
-
read(size=-1): Read entire file orsizebytes. -
readline(): Read one line (including newline). -
readlines(): Read all lines into a list. -
Best practice for large files: Iterate directly over file object (memory efficient):
with open('file.txt') as f: for line in f: process(line)
Writing to Files
-
write(str): Write a string. -
writelines(iterable): Write an iterable of strings (no newlines added automatically).
Context Managers (with Statement)
-
Ensures proper acquisition and release of resources (file automatically closed).
-
Syntax:
with open('file.txt', 'r') as f: data = f.read() # f is closed here, even if exception occurs
Working with CSV/JSON
-
CSV: Use
csvmodule.import csv with open('data.csv') as f: reader = csv.reader(f) for row in reader: print(row) -
JSON: Use
jsonmodule.import json data = json.load(f) # Read JSON from file json.dump(data, f) # Write JSON to file
2.5 Error and Exception Handling
Syntax Errors vs. Exceptions
-
Syntax errors: Detected at compile time (e.g., missing colon).
-
Exceptions: Errors detected during execution (e.g.,
IndexError).
Common Built-in Exceptions
| Exception | Cause |
|---|---|
ValueError |
Right type, inappropriate value (e.g., int('abc')). |
TypeError |
Operation on wrong type (e.g., 'a' + 1). |
IndexError |
Sequence index out of range. |
KeyError |
Dict key not found. |
FileNotFoundError |
File does not exist. |
ZeroDivisionError |
Division/modulo by zero. |
try...except Block
try:
# risky code
result = 10 / 0
except ZeroDivisionError as e:
# handle specific exception
print(f"Error: {e}")
except (TypeError, ValueError):
# handle multiple exceptions
print("Type or value error")
except Exception as e:
# catch-all (use sparingly)
print(f"Unexpected: {e}")
else and finally Clauses
-
else: Executes if no exception occurs intryblock. -
finally: Always executes (cleanup), regardless of exceptions.try: f = open('file.txt') except FileNotFoundError: print("Not found") else: print("File opened") data = f.read() finally: f.close() # Guaranteed cleanup
Raising Exceptions
-
raise ExceptionType("message")to trigger an exception. -
Re-raise with
raisealone insideexceptblock. -
Custom exceptions: Define by subclassing
Exception.
Assertions
-
assert condition, "message"– for debugging/internal checks. -
Disabled with
-O(optimize) flag; not for production error handling.
[!TIP]
Best Practice: Catch specific exceptions, not bare
except:. Usefinallyfor resource cleanup (thoughwithis preferred for files).
2.6 Advanced Topics & Best Practices
Shallow vs. Deep Copy
| Type | Module | Behavior |
|---|---|---|
| Shallow | copy.copy() |
New container, references to same nested objects. |
| Deep | copy.deepcopy() |
New container, recursively copies all nested objects. |
- Implication: Modifying a nested mutable object in a shallow copy affects original.
Common Pitfalls & Solutions
| Pitfall | Problem | Solution |
|---|---|---|
| Mutable default arguments | Default list/dict shared across calls. | Use None and initialize inside: def func(lst=None): lst = lst or [] |
| Loop variable leakage | Loop variable retains last value after loop. | Use distinct variable names or encapsulate in function. |
| Integer vs. string comparison | '3' == 3 is False (type mismatch). |
Explicitly convert types: int(s) == 3. |
Code Style (PEP 8)
-
Naming:
snake_casefor functions/variables,CamelCasefor classes. -
Indentation: 4 spaces per level.
-
Line length: Max 79 characters (code), 72 (comments).
-
Whitespace: Around operators, after commas, but not inside brackets.
-
Imports: Standard library → third-party → local, each group separated by blank line.
Debugging Techniques
-
print(): Insert at关键 points to inspect variables. -
loggingmodule: More flexible thanprint; levels (DEBUG, INFO, WARNING, ERROR).import logging logging.basicConfig(level=logging.DEBUG) logging.debug("Variable x = %s", x) -
Assertions: Check invariants during development.
Key Formulas & Concepts Summary
-
Time Complexity (common operations):
-
List
append(): \boxed{O(1)} (amortized) -
Dict
get()/set(): \boxed{O(1)} average -
List
in(search): \boxed{O(n)} -
Set
in: \boxed{O(1)} average
-
-
Lambda: \boxed{\lambda\ x:\ x*2}
-
List Comprehension: \boxed{[x**2\ for\ x\ in\ range(10)\ if\ x%2==0]}
-
Context Manager: Ensures \boxed{\text{automatic resource cleanup}}