Python Programming
From Beginner to Practical Developer — A 5-Page Reference Guide
Page 1 — Python Basics & Data Types
Python is the world's most popular programming language (TIOBE Index 2024). It's used in web
development, data science, machine learning, automation, finance, and scientific research. Its
philosophy: 'There should be one obvious way to do it.'
Core Data Types:
Type Example Notes
int x = 42 Arbitrary precision integers
float pi = 3.14159 IEEE 754 double precision
str name = "Akash" Immutable; f-strings for formatting
bool flag = True Subclass of int; True=1, False=0
list nums = [1,2,3] Mutable ordered sequence
tuple coords = (x, y) Immutable ordered; faster than list
dict d = {"key": val} Hash map; O(1) lookup
set s = {1,2,3} Unordered unique elements
Page 2 — Control Flow, Functions & OOP
Python's readability comes from meaningful indentation and clean syntax. Understanding these
patterns is the foundation of all Python code.
Control Flow:
• if/elif/else: Standard branching. Python uses elif (not else if).
• for loop: Iterates over any iterable. for i in range(10): | for item in list:
• while loop: Runs while condition is True. Use break to exit, continue to skip iteration.
• List comprehension: [x**2 for x in range(10) if x%2==0] — Pythonic and fast.
• try/except/finally: Exception handling. Always catch specific exceptions, not bare except.
Functions:
def function_name(param, *args, default=None, **kwargs): — Python supports positional args,
keyword args, *args (tuple of extra positional args), and **kwargs (dict of extra keyword args).
Lambda functions: square = lambda x: x**2
Object-Oriented Programming (OOP):
Python is multi-paradigm but OOP is central. Classes use __init__ for constructor. Key concepts:
Inheritance (class Dog(Animal):), Encapsulation (self._private), Polymorphism (method
overriding), and Magic methods (__str__, __len__, __add__, __repr__).
Page 3 — Essential Libraries
Python's power comes from its ecosystem. The Python Package Index (PyPI) has over 500,000
packages. Here are the most important ones by domain:
Data Science Stack:
• NumPy: N-dimensional arrays, mathematical functions, vectorized operations. The
foundation everything else is built on.
• Pandas: DataFrame operations — think Excel in Python but 100× more powerful. read_csv,
groupby, merge, pivot_table.
• Matplotlib / Seaborn: Visualization. Matplotlib for control; Seaborn for beautiful statistical
plots with minimal code.
• Scikit-learn: Machine learning. 50+ algorithms with consistent API: [Link](X,y) |
[Link](X).
Web & API Development:
• requests: HTTP library. [Link](url, headers={}, params={}) — essential for any API
work.
• FastAPI: Modern async API framework. Auto-generates Swagger docs. 3× faster than
Flask.
• Flask: Lightweight web framework. [Link]('/path') decorator. Great for prototyping.
Automation & Finance:
• Selenium / Playwright: Browser automation. Scraping, testing, filling forms.
• yfinance: Yahoo Finance data. [Link]('AAPL', start='2020-01-01')
• schedule / APScheduler: Run Python functions on schedule (every 5 min, daily 9:15 AM,
etc.)
Page 4 — Performance, Async & Best Practices
Writing code that works is step 1. Writing code that's fast, maintainable, and professional is step
2. Here's what separates junior from senior Python developers.
Performance Techniques:
• List comprehensions over for loops: 2–5× faster due to C-level optimization.
• NumPy vectorization: Never loop over a NumPy array; use vectorized operations
(100–1000× speedup).
• ThreadPoolExecutor: For I/O-bound tasks (API calls, file reads). Runs multiple threads
simultaneously.
• ProcessPoolExecutor: For CPU-bound tasks. Bypasses Python's GIL by using separate
processes.
• Caching with functools.lru_cache: Memoizes function results. Massive speedup for
recursive/repetitive calls.
Async Programming:
asyncio allows concurrent execution without threads. async def + await syntax. Best for: web
servers handling many concurrent connections, scraping hundreds of URLs simultaneously, any
I/O-bound workload. Use aiohttp instead of requests for async HTTP.
Professional Best Practices:
• Type hints: def add(a: int, b: int) -> int: — improves IDE support and catches bugs.
• Dataclasses / Pydantic: Structured data with validation. Replaces messy dict handling.
• Environment variables: Never hardcode secrets — use python-dotenv + .env file.
• Logging over print: import logging. Levels: DEBUG, INFO, WARNING, ERROR, CRITICAL.
Page 5 — Python in Finance & Trading
Python has become the dominant language in quantitative finance — from hedge fund research
desks to retail algo traders. The libraries, APIs, and community support are unmatched.
Trading System Architecture:
A complete Python trading system has 5 layers:
1. Data Layer: Fetch OHLCV data from broker API (Fyers, Zerodha) or yfinance. Store in
pandas DataFrame or SQLite.
2. Signal Layer: Calculate indicators (EMA, Supertrend, RSI). Generate buy/sell signals as
boolean columns.
3. Risk Layer: Calculate position size from capital and stop loss. Check daily loss limits.
4. Execution Layer: Place orders via broker API. Handle order status, partial fills, rejections.
5. Monitoring Layer: Logging, Telegram alerts, P&L; tracking, performance metrics.
Key Python Concepts for Trading:
• Vectorized backtesting: Apply signals across entire historical dataset at once using
pandas — no slow row-by-row loops.
• Batch API calls: Always fetch data in batches (50 symbols per call) and use
ThreadPoolExecutor for parallel fetching.
• Timezone handling: Always work in IST (Asia/Kolkata) for Indian markets. Use
[Link].tz_convert().
• Market hours check: Always validate 9:15 AM – 3:30 PM IST before placing any orders.
• Error handling on orders: Network failures happen. Wrap every API call in try/except with
retry logic.
Python guide compiled from 30+ years of language development and practical usage patterns.