Skip to content

Python Basics: Quick Reference for Developers

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.

Python variables are names bound to objects. No declaration keyword required.

order_id = "ORD-001" # str
quantity = 12 # int
price = 49.95 # float
active = True # bool
notes = None # NoneType
# Type hints (annotation — not enforced at runtime)
subtotal: float = 100.0

Variables and types in depth →

# list: ordered, mutable, duplicates allowed
pending = ["ORD-001", "ORD-002", "ORD-003"]
pending.append("ORD-004")
pending.pop(0) # remove first
# tuple: ordered, immutable
point = (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 values
tags = {"sale", "electronics"}
tags.add("warranty")
print("sale" in tags) # O(1)

Collections in depth →

# if / elif / else
if quantity > 10:
print("bulk order")
elif quantity > 0:
print("standard order")
else:
print("empty order")
# for loop
for order_id in pending:
print(order_id)
# for with index
for i, item in enumerate(pending):
print(i, item)
# range
for i in range(5): # 0, 1, 2, 3, 4
print(i)
# while
count = 3
while count > 0:
print(count)
count -= 1
# list comprehension
prices = [10.0, 20.0, 30.0]
discounted = [p * 0.9 for p in prices]
large = [p for p in prices if p > 15]

Control flow in depth →

def calculate_total(subtotal: float, tax_rate: float = 0.08) -> float:
"""Return subtotal plus tax."""
return round(subtotal * (1 + tax_rate), 2)
# Keyword arguments
total = calculate_total(subtotal=100.0, tax_rate=0.05)
# *args and **kwargs
def log(*args, **kwargs):
for a in args:
print(a)
for k, v in kwargs.items():
print(f"{k}={v}")
# Lambda
double = lambda x: x * 2
items = [3, 1, 4, 1, 5]
items.sort(key=lambda x: -x) # sort descending

Functions in depth →

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.0
print(isinstance(o, Order)) # True

OOP in depth →

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 exception
finally:
print("Always runs") # runs always
# Raise
def check_amount(amount: float) -> None:
if amount < 0:
raise ValueError(f"Amount cannot be negative: {amount}")

Error handling in depth →

from pathlib import Path
# Write
Path("report.txt").write_text("Order Report\n", encoding="utf-8")
# Read
content = Path("report.txt").read_text(encoding="utf-8")
# Context manager style
with open("report.txt", "a", encoding="utf-8") as f:
f.write("ORD-001 confirmed\n")

File I/O in depth →

# Import a module
import math
print(math.sqrt(16)) # 4.0
# Import specific names
from pathlib import Path
from datetime import datetime, timedelta
# Import with alias
import numpy as np
# Relative import (inside a package)
from .orders import calculate_total
from ..utils import format_id

Modules and packages in depth →

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 aliases
OrderID = str
Prices = list[float]

Type hints feature guide →

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

The numbered articles in this section cover each topic in depth with worked examples and interview questions:

  1. Variables and types
  2. Control flow
  3. Functions
  4. Data structures
  5. Modules and packages
  6. OOP
  7. Error handling
  8. File I/O
  9. Standard library

The Python features section goes deeper on individual language features.