nova / python.txt
crazysanthosh's picture
Upload 25 files
7fde9b9 verified
Raw History Blame Contribute Delete
8.93 kB
## Python Basics
Definition: Python is a high-level, interpreted, dynamically-typed programming language known for its clean syntax and readability.
Explanation: Python uses indentation instead of braces for code blocks. It supports multiple paradigms: procedural, OOP, and functional. Everything in Python is an object. The standard library is extensive ("batteries included"). Python runs on CPython (the default), PyPy, Jython, and more.
Example: Print "Hello World" in Python: print("Hello, World!")
Code Example:
```python
# Basic Python syntax
name = "Alice"
age = 30
if age >= 18:
print(f"{name} is an adult")
else:
print(f"{name} is a minor")
# List comprehension
squares = [x**2 for x in range(10)]
print(squares) # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
```
Best Practices: Follow PEP 8 style guide. Use f-strings for formatting. Prefer list comprehensions over loops for simple transformations. Use virtual environments (venv).
Common Errors: Mutable default arguments in functions. Forgetting that strings are immutable. Using == to compare None (use is None instead).
Interview Questions: What is the GIL in Python? Explain the difference between is and ==. What are *args and **kwargs?
## Python Decorators
Definition: Decorators are functions that wrap another function to modify or extend its behavior without changing its source code.
Explanation: A decorator takes a function as input, adds some functionality, and returns a new function. They use the @syntax as syntactic sugar. Common uses: logging, timing, authentication, caching, and validation. Python's built-in decorators include @staticmethod, @classmethod, and @property.
Example: A timer decorator measures function execution time.
Code Example:
```python
import time
from functools import wraps
def timer(func):
@wraps(func) # Preserves func metadata
def wrapper(*args, **kwargs):
start = time.time()
result = func(*args, **kwargs)
end = time.time()
print(f"{func.__name__} took {end-start:.4f}s")
return result
return wrapper
@timer
def slow_function():
time.sleep(1)
slow_function() # slow_function took 1.0012s
```
Best Practices: Always use @wraps to preserve function metadata. Stack decorators in the right order (they apply bottom-up). Use functools.lru_cache or functools.cache for memoization.
Common Errors: Forgetting @wraps causes __name__ to show the wrapper name. Applying decorators that return None instead of the wrapped function. Calling the decorated function instead of returning it.
Interview Questions: How does @wraps work? Explain the execution order of stacked decorators. How would you implement a rate-limiting decorator?
## Python List Comprehensions
Definition: List comprehensions provide a concise way to create lists from iterables with optional filtering.
Explanation: Syntax: [expression for item in iterable if condition]. They are faster than equivalent for-loops because they're optimized at the C level. Dict comprehensions {k:v for k,v in items}, set comprehensions {x for x in items}, and generator expressions (x for x in items) use similar syntax.
Example: Filter even numbers from a list and square them in one line.
Code Example:
```python
# List comprehension
evens_squared = [x**2 for x in range(20) if x % 2 == 0]
# [0, 4, 16, 36, 64, 100, 144, 196, 256, 324]
# Dict comprehension
word_lengths = {word: len(word) for word in ["python", "java", "go"]}
# {'python': 6, 'java': 4, 'go': 2}
# Generator (memory efficient)
gen = (x**2 for x in range(1000000))
print(next(gen)) # 0 - computed lazily
```
Best Practices: Keep comprehensions simple and readable. For complex logic, use a regular for loop. Use generators when working with large datasets to avoid loading all data into memory.
Common Errors: Nested comprehensions that become unreadable. Using comprehensions with side effects (e.g., printing inside). Forgetting that generator expressions are lazy.
Interview Questions: How do comprehensions differ from map/filter? When should you use a generator expression vs a list comprehension? What is a generator?
## Python Classes and OOP
Definition: Python classes are blueprints for creating objects. Python supports full OOP with inheritance, encapsulation, and polymorphism.
Explanation: __init__ is the constructor. __str__/__repr__ control string representation. Dunder (double underscore) methods allow operator overloading. Python supports multiple inheritance. @property creates computed attributes. @classmethod gets the class itself, @staticmethod is a plain utility function.
Example: A BankAccount class with deposit/withdraw methods and balance tracking.
Code Example:
```python
class BankAccount:
interest_rate = 0.05 # Class variable
def __init__(self, owner, balance=0):
self.owner = owner
self._balance = balance # Protected
@property
def balance(self):
return self._balance
def deposit(self, amount):
if amount > 0:
self._balance += amount
def __repr__(self):
return f"BankAccount({self.owner!r}, {self._balance})"
acc = BankAccount("Alice", 1000)
acc.deposit(500)
print(acc.balance) # 1500
print(acc) # BankAccount('Alice', 1500)
```
Best Practices: Use @property instead of getter/setter methods. Prefix private attributes with _ or __. Implement __repr__ for all classes for easier debugging.
Common Errors: Mutable class-level variables shared between instances. Not calling super().__init__() in subclasses. Confusing self with cls in class methods.
Interview Questions: What is the MRO (Method Resolution Order)? Explain metaclasses. What is the difference between __str__ and __repr__?
## Python Error Handling
Definition: Python uses try/except/finally blocks to handle exceptions gracefully without crashing the program.
Explanation: Exceptions are objects derived from BaseException. Python has many built-in exceptions (ValueError, TypeError, FileNotFoundError, etc.). You can create custom exception classes. raise re-raises the current exception or raises a new one. The else block runs if no exception occurs. finally always runs (for cleanup).
Example: Opening a file — handle cases where the file doesn't exist.
Code Example:
```python
class InsufficientFundsError(Exception):
"""Custom exception"""
pass
def withdraw(balance, amount):
if amount > balance:
raise InsufficientFundsError(
f"Cannot withdraw {amount}, balance is {balance}"
)
return balance - amount
try:
new_balance = withdraw(100, 200)
except InsufficientFundsError as e:
print(f"Error: {e}")
except (TypeError, ValueError) as e:
print(f"Invalid input: {e}")
else:
print(f"Success! New balance: {new_balance}")
finally:
print("Transaction complete")
```
Best Practices: Catch specific exceptions, not bare except. Create custom exception classes for domain-specific errors. Use context managers (with statement) for resource cleanup.
Common Errors: Using bare except: catches even KeyboardInterrupt. Swallowing exceptions silently. Raising Exception directly instead of a custom subclass.
Interview Questions: What is the difference between Exception and BaseException? When would you use raise from? How do context managers relate to exception handling?
## Python Async/Await
Definition: Python's asyncio library provides asynchronous I/O using coroutines with async/await syntax for high-concurrency I/O-bound tasks.
Explanation: async def defines a coroutine. await suspends execution until the awaited task completes, allowing other tasks to run. asyncio.gather() runs multiple coroutines concurrently. This is NOT parallelism — it's cooperative multitasking on a single thread. Best for I/O tasks (network calls, DB queries), not CPU-bound work.
Example: Fetch multiple URLs concurrently instead of sequentially for 10x speedup.
Code Example:
```python
import asyncio
import aiohttp
async def fetch_url(session, url):
async with session.get(url) as response:
return await response.text()
async def main():
urls = [
"https://api.example.com/data/1",
"https://api.example.com/data/2",
]
async with aiohttp.ClientSession() as session:
tasks = [fetch_url(session, url) for url in urls]
results = await asyncio.gather(*tasks)
return results
asyncio.run(main())
```
Best Practices: Use asyncio.gather() for concurrent tasks. Use aiohttp for async HTTP, asyncpg for async DB. Don't mix sync and async code (it blocks the event loop).
Common Errors: Calling time.sleep() instead of asyncio.sleep() in async code. Forgetting to await a coroutine (returns coroutine object, not result). Using CPU-bound tasks with asyncio (use multiprocessing instead).
Interview Questions: What is the difference between asyncio, threading, and multiprocessing? Explain the event loop. When should you NOT use async/await?