Python Basics: Quick Reference for Developers
What this page covers
Section titled “What this page covers”A quick-reference guide to Python syntax for developers who already program in another language. Use it to get up to speed with Python’s idioms before reading the full topic articles. Each section links to a deeper article.
Variables and types
Section titled “Variables and types”Python variables are names bound to objects. No declaration keyword required.
order_id = "ORD-001" # strquantity = 12 # intprice = 49.95 # floatactive = True # boolnotes = None # NoneType
# Type hints (annotation — not enforced at runtime)subtotal: float = 100.0Variables and types in depth →
Collections
Section titled “Collections”# list: ordered, mutable, duplicates allowedpending = ["ORD-001", "ORD-002", "ORD-003"]pending.append("ORD-004")pending.pop(0) # remove first
# tuple: ordered, immutablepoint = (4, 7)x, y = point # unpack
# dict: key-value, ordered (Python 3.7+)order = {"id": "ORD-001", "amount": 108.0}order["status"] = "confirmed"value = order.get("discount", 0.0) # safe access
# set: unordered, unique valuestags = {"sale", "electronics"}tags.add("warranty")print("sale" in tags) # O(1)Control flow
Section titled “Control flow”# if / elif / elseif quantity > 10: print("bulk order")elif quantity > 0: print("standard order")else: print("empty order")
# for loopfor order_id in pending: print(order_id)
# for with indexfor i, item in enumerate(pending): print(i, item)
# rangefor i in range(5): # 0, 1, 2, 3, 4 print(i)
# whilecount = 3while count > 0: print(count) count -= 1
# list comprehensionprices = [10.0, 20.0, 30.0]discounted = [p * 0.9 for p in prices]large = [p for p in prices if p > 15]Functions
Section titled “Functions”def calculate_total(subtotal: float, tax_rate: float = 0.08) -> float: """Return subtotal plus tax.""" return round(subtotal * (1 + tax_rate), 2)
# Keyword argumentstotal = calculate_total(subtotal=100.0, tax_rate=0.05)
# *args and **kwargsdef log(*args, **kwargs): for a in args: print(a) for k, v in kwargs.items(): print(f"{k}={v}")
# Lambdadouble = lambda x: x * 2items = [3, 1, 4, 1, 5]items.sort(key=lambda x: -x) # sort descendingClasses
Section titled “Classes”class Order: tax_rate = 0.08 # class attribute
def __init__(self, order_id: str, amount: float) -> None: self.order_id = order_id self.amount = amount self.status = "pending"
def total(self) -> float: return round(self.amount * (1 + self.tax_rate), 2)
def __str__(self) -> str: return f"Order({self.order_id})"
class ShippedOrder(Order): def __init__(self, order_id: str, amount: float, tracking: str) -> None: super().__init__(order_id, amount) self.tracking = tracking self.status = "shipped"
o = Order("ORD-001", 100.0)print(o.total()) # 108.0print(isinstance(o, Order)) # TrueError handling
Section titled “Error handling”try: result = int("abc")except ValueError as e: print(f"Bad input: {e}")except (TypeError, AttributeError): print("Type problem")else: print("Success") # runs only if no exceptionfinally: print("Always runs") # runs always
# Raisedef check_amount(amount: float) -> None: if amount < 0: raise ValueError(f"Amount cannot be negative: {amount}")File I/O
Section titled “File I/O”from pathlib import Path
# WritePath("report.txt").write_text("Order Report\n", encoding="utf-8")
# Readcontent = Path("report.txt").read_text(encoding="utf-8")
# Context manager stylewith open("report.txt", "a", encoding="utf-8") as f: f.write("ORD-001 confirmed\n")Modules and imports
Section titled “Modules and imports”# Import a moduleimport mathprint(math.sqrt(16)) # 4.0
# Import specific namesfrom pathlib import Pathfrom datetime import datetime, timedelta
# Import with aliasimport numpy as np
# Relative import (inside a package)from .orders import calculate_totalfrom ..utils import format_idModules and packages in depth →
Type hints quick reference
Section titled “Type hints quick reference”from typing import Optional# Python 3.10+ can use X | None instead of Optional[X]
def greet(name: str) -> str: ...def process(items: list[str]) -> dict[str, int]: ...def find(key: str) -> str | None: ... # Python 3.10+
# Type aliasesOrderID = strPrices = list[float]Python vs C# / JavaScript quick comparison
Section titled “Python vs C# / JavaScript quick comparison”| Feature | Python | C# | JavaScript |
|---|---|---|---|
| Variable declaration | x = 1 |
int x = 1; |
let x = 1; |
| Null / empty | None |
null |
null / undefined |
| String interpolation | f"Hello {name}" |
$"Hello {name}" |
`Hello ${name}` |
| List / array | list |
List<T> |
Array |
| Dictionary / map | dict |
Dictionary<K,V> |
Object / Map |
| Lambda | lambda x: x * 2 |
x => x * 2 |
x => x * 2 |
| Class inheritance | class Dog(Animal): |
class Dog : Animal |
class Dog extends Animal |
| Import | import math |
using System; |
import math from "math" |
| Package manager | pip |
NuGet |
npm |
| Async | async def / await |
async Task / await |
async function / await |
Where to go next
Section titled “Where to go next”The numbered articles in this section cover each topic in depth with worked examples and interview questions:
- Variables and types
- Control flow
- Functions
- Data structures
- Modules and packages
- OOP
- Error handling
- File I/O
- Standard library
The Python features section goes deeper on individual language features.