Python Commands: The Complete Reference (Built-ins, Keywords, CLI, and Modern Idioms)
"Commands" in Python is a loose term — it covers built-in functions, language keywords, REPL helpers, and the python and pip shell tools. This guide is the complete reference: every built-in you'll use day to day, every keyword and control structure, the file I/O patterns Python developers actually write, async/await, the standard-library modules worth knowing, and the CLI commands that make python and pip productive.
Quick cheatsheet
| Category | Most-used commands |
|---|---|
| I/O | print(), input(), open() |
| Inspection | type(), id(), dir(), help(), repr() |
| Math | abs(), round(), min(), max(), sum(), pow(), divmod() |
| Iteration | range(), enumerate(), zip(), map(), filter(), reversed(), sorted() |
| Conversion | int(), float(), str(), bool(), list(), tuple(), set(), dict(), bytes() |
| Sizing | len(), any(), all() |
| Control flow keywords | if, elif, else, for, while, break, continue, pass, match, case |
| Function keywords | def, return, yield, lambda, async, await |
| Class keywords | class, self (convention), super, @property, @staticmethod, @classmethod |
| Error handling | try, except, else, finally, raise, assert, with |
| Modules | import, from, as, __import__ |
| CLI | python -V, python -m, python -c, pip install, pip freeze |
Input and output
print()
print("Hello, world!")
print("a", "b", "c", sep="-") # a-b-c
print("no newline", end="")
print(f"x = {x}, y = {y}") # f-strings (Python 3.6+)
print("redirect", file=sys.stderr)
print("flushed", flush=True)input()
name = input("What is your name? ")
age = int(input("Age? ")) # always returns str — cast as neededFile I/O — the modern idiom
Always use with so files close automatically, even if an exception fires:
with open("data.txt", "r", encoding="utf-8") as f:
contents = f.read()
# Line by line — memory-efficient
with open("big.log") as f:
for line in f:
process(line)
# Write
with open("out.txt", "w", encoding="utf-8") as f:
f.write("hello\n")
# Append
with open("out.txt", "a") as f:
f.write("more\n")For binary data, use mode "rb"/"wb". For UTF-8-anywhere code, always pass encoding="utf-8" — the default is platform-dependent and a frequent source of cross-platform bugs.
JSON
import json
data = json.loads('{"name": "Ada"}')
text = json.dumps({"x": 1}, indent=2)
with open("data.json") as f:
data = json.load(f)
with open("out.json", "w") as f:
json.dump(data, f, indent=2)Essential built-in functions
Inspection
type(42) # <class 'int'>
type([1, 2]) # <class 'list'>
isinstance(x, int) # True/False — preferred over type(x) == int
id(x) # memory address (object identity)
dir(obj) # all attributes and methods
help(str.split) # docstring
repr(obj) # debug-friendly stringMath
abs(-5) # 5
round(3.14159, 2) # 3.14
round(2.5) # 2 — banker's rounding (round-half-to-even)
min(1, 2, 3) # 1
max([4, 5, 6]) # 6
sum(range(10)) # 45
pow(2, 10) # 1024
divmod(17, 5) # (3, 2) — quotient and remainderIteration helpers
range(5) # 0, 1, 2, 3, 4
range(2, 8) # 2..7
range(0, 20, 3) # 0, 3, 6, ..., 18
enumerate(["a","b","c"])
# (0, 'a'), (1, 'b'), (2, 'c')
zip([1,2,3], ["a","b","c"])
# (1,'a'), (2,'b'), (3,'c')
reversed([1, 2, 3]) # 3, 2, 1
sorted([3, 1, 2]) # [1, 2, 3]
sorted(words, key=len)
sorted(rows, key=lambda r: (-r["score"], r["name"]))Type conversion
int("42") # 42
int("ff", 16) # 255 — base-16
float("3.14") # 3.14
str(123) # "123"
list("abc") # ['a', 'b', 'c']
tuple([1, 2]) # (1, 2)
set([1, 1, 2, 3]) # {1, 2, 3}
dict([("a", 1), ("b", 2)]) # {'a': 1, 'b': 2}
bytes("hi", "utf-8") # b'hi'Boolean reductions
any([0, 0, 1, 0]) # True
all([1, 2, 3]) # True
bool(0) # False
bool([]) # False
bool([0]) # True — non-empty list, even with falsy contentsControl flow
if / elif / else
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
elif score >= 70:
grade = "C"
else:
grade = "F"match / case (Python 3.10+)
def http_status(code):
match code:
case 200 | 201 | 204:
return "ok"
case 301 | 302:
return "redirect"
case 400 | 401 | 403 | 404:
return "client error"
case _ if 500 <= code < 600:
return "server error"
case _:
return "unknown"Structural pattern matching also destructures sequences, mappings, and class instances.
Loops
for item in items:
process(item)
else:
print("loop completed without break") # the rare for-else clause
for i, item in enumerate(items):
print(i, item)
while not done:
done = step()
for x in range(10):
if x == 5:
break
if x % 2 == 0:
continue
print(x)Functions
Definition and arguments
def greet(name, greeting="Hello"):
return f"{greeting}, {name}!"
greet("Ada") # 'Hello, Ada!'
greet("Ada", greeting="Hi") # 'Hi, Ada!'
# *args and **kwargs
def log(*args, **kwargs):
print(args, kwargs)
log(1, 2, level="info")
# (1, 2) {'level': 'info'}Type hints
def add(a: int, b: int) -> int:
return a + b
from typing import Optional, Iterable
def total(values: Iterable[float], default: Optional[float] = None) -> float:
items = list(values)
if not items:
return default if default is not None else 0.0
return sum(items)Lambdas and functional helpers
double = lambda x: x * 2
list(map(lambda x: x ** 2, range(5))) # [0, 1, 4, 9, 16]
list(filter(lambda x: x > 0, [-2, -1, 0, 1, 2])) # [1, 2]
from functools import reduce
reduce(lambda a, b: a + b, [1, 2, 3, 4]) # 10Most functional patterns are more readable as comprehensions:
[x ** 2 for x in range(5)] # [0, 1, 4, 9, 16]
[x for x in nums if x > 0] # filter
{w: len(w) for w in words} # dict comprehension
{n % 10 for n in numbers} # set comprehensionGenerators and yield
def fibonacci(n):
a, b = 0, 1
for _ in range(n):
yield a
a, b = b, a + b
list(fibonacci(8)) # [0, 1, 1, 2, 3, 5, 8, 13]
# Generator expression — no list materialized
total = sum(x ** 2 for x in range(1_000_000))Decorators
from functools import wraps
def timed(fn):
@wraps(fn)
def wrapper(*args, **kwargs):
import time
start = time.perf_counter()
result = fn(*args, **kwargs)
print(f"{fn.__name__}: {time.perf_counter() - start:.3f}s")
return result
return wrapper
@timed
def slow_fn():
sum(range(10_000_000))Errors and exceptions
try:
n = int(user_input)
except ValueError as e:
print(f"not a number: {e}")
except (TypeError, AttributeError):
print("wrong type")
else:
print("parsed", n) # only runs if no exception
finally:
print("always runs")Raising and custom exceptions
if amount < 0:
raise ValueError(f"amount must be non-negative, got {amount}")
class TransientError(Exception):
"""Raised when a remote call should be retried."""
raise TransientError("upstream 503") from original_exceptionAssertions
assert n > 0, f"expected positive, got {n}"assert is for invariants you'd accept removing in production. Don't use it for input validation — running Python with -O strips assertions out.
Classes
class Account:
def __init__(self, owner, balance=0):
self.owner = owner
self._balance = balance
@property
def balance(self):
return self._balance
def deposit(self, amount):
if amount < 0:
raise ValueError("amount must be non-negative")
self._balance += amount
def __repr__(self):
return f"Account({self.owner!r}, balance={self._balance})"
class SavingsAccount(Account):
def __init__(self, owner, balance=0, rate=0.02):
super().__init__(owner, balance)
self.rate = rate
a = SavingsAccount("Ada", 100, rate=0.03)
a.deposit(50)
print(a.balance) # 150Dataclasses (Python 3.7+)
from dataclasses import dataclass, field
@dataclass
class Point:
x: float
y: float
label: str = ""
@dataclass(frozen=True)
class Config:
debug: bool = False
tags: list = field(default_factory=list)Async / await
Concurrent I/O without threads:
import asyncio
async def fetch(url):
# imagine an HTTP call here
await asyncio.sleep(1)
return f"data from {url}"
async def main():
urls = ["a", "b", "c"]
results = await asyncio.gather(*(fetch(u) for u in urls))
print(results)
asyncio.run(main())Use async def to define a coroutine; await to wait on another coroutine; asyncio.run to start the event loop. asyncio.gather runs coroutines concurrently and returns when all complete.
Async iteration
async for chunk in stream:
process(chunk)
async with httpx.AsyncClient() as client:
response = await client.get("https://api.example.com")Modules and imports
import math
math.sqrt(16)
from math import sqrt, pi
sqrt(16)
import numpy as np
import pandas as pd
from collections import defaultdict, Counter, deque, OrderedDict
from pathlib import PathStandard library worth knowing
| Module | Use it for |
|---|---|
os / os.path | Environment vars, paths, file ops |
pathlib | Modern path manipulation (preferred over os.path) |
sys | Argv, stdin/stdout/stderr, exit, exceptions |
json | JSON serialization |
csv | CSV read/write |
re | Regular expressions |
datetime | Dates and times |
collections | Counter, defaultdict, deque, namedtuple |
itertools | chain, groupby, combinations, product, islice |
functools | lru_cache, partial, reduce, wraps |
typing | Type hints (Optional, List, Dict, Callable) |
asyncio | Async runtime |
subprocess | Run shell commands |
logging | Structured logging (use this, not print) |
argparse | Command-line argument parsing |
unittest | Test framework (or use pytest) |
pathlib: the modern way to work with paths
from pathlib import Path
p = Path("data") / "users.json"
p.exists()
p.is_file()
p.read_text(encoding="utf-8")
p.write_text("hello\n", encoding="utf-8")
p.parent
p.suffix # '.json'
p.stem # 'users'
list(Path("logs").glob("*.log"))The python command-line interface
| Flag | Effect |
|---|---|
python -V | Print version |
python script.py | Run a script |
python -c "print(1+1)" | Run a one-liner |
python -m module | Run a module as a script |
python -i script.py | Run, then drop into REPL with state preserved |
python -O | Strip assert statements (basic optimizations) |
python -OO | Also strip docstrings |
python -u | Unbuffered stdout/stderr |
python -X dev | Developer mode — extra warnings |
python -W error | Turn warnings into errors |
-m modules you'll actually use
python -m venv .venv # create a virtual environment
python -m pip install requests # always-correct way to invoke pip
python -m http.server 8000 # serve the current directory over HTTP
python -m json.tool data.json # pretty-print JSON
python -m timeit "sum(range(1000))" # benchmark a snippet
python -m unittest discover # run tests
python -m pdb script.py # debug a script
python -m site # show site-packages infoVirtual environments
# Create
python -m venv .venv
# Activate
source .venv/bin/activate # macOS/Linux
.venv\Scripts\activate # Windows
# Deactivate
deactivateAlways work inside a virtual environment per project. It isolates dependencies and stops you from polluting the system Python. Modern alternatives: uv, poetry, pdm, hatch, pipenv.
pip — installing packages
pip install requests
pip install "requests>=2.31"
pip install -e . # editable install of the current project
pip install -r requirements.txt
pip install --upgrade requests
pip install package-name --target=./libs
pip uninstall requests
pip list # installed packages
pip show requests # package metadata
pip freeze > requirements.txt # snapshot deps
pip check # verify dependency consistency
pip install --dry-run requests # show what would happenAvoid sudo pip
Installing packages globally with sudo pip install ... is a recipe for tangled environments and broken system tools. Use a virtual environment, pip install --user, or a tool like uv or pipx instead.
REPL helpers
Inside the interactive Python prompt:
help(str) # full help on the str type
help(str.split) # help on a single method
dir(obj) # list every attribute
type(obj)
exit() # or Ctrl-D
import this # the Zen of PythonFor an upgraded REPL, install IPython or use python -m bpython — both add tab completion, syntax highlighting, and rich tracebacks.
Useful Python idioms
Swap two variables
a, b = b, aUnpack into multiple names
first, *rest = [1, 2, 3, 4] # first=1, rest=[2,3,4]
*head, last = "abcd" # head=['a','b','c'], last='d'Default dict pattern
from collections import defaultdict
groups = defaultdict(list)
for user in users:
groups[user.team].append(user)Counting occurrences
from collections import Counter
Counter("mississippi").most_common(3)
# [('i', 4), ('s', 4), ('p', 2)]Memoize a pure function
from functools import lru_cache
@lru_cache(maxsize=None)
def fib(n):
return n if n < 2 else fib(n-1) + fib(n-2)Walrus operator (Python 3.8+)
while (line := f.readline()):
process(line)
if (n := len(items)) > 100:
print(f"too many: {n}")Picking a Python version
As of May 2026, the actively supported versions are Python 3.11, 3.12, 3.13, and 3.14. New projects should use 3.12 or later. 3.10 added match; 3.11 made the interpreter ~25% faster; 3.12 polished f-strings and per-interpreter GIL groundwork; 3.13 made the GIL optional in build mode. Don't start anything new on Python 2 — it has been end-of-life since January 2020.
Frequently asked questions
Is print a function or a statement in Python?
A function in Python 3 (call it as print(...)). It was a statement in Python 2 — one of the most visible Python 2-to-3 differences.
What's the difference between == and is in Python?
== compares values. is compares object identity (same memory address). Use is only with None, True, False, and intentionally singleton objects: x is None. Use == for values: x == 5.
What does __init__ do?
__init__ is a class's constructor — it initializes a new instance after Python creates it. It's not a "factory" that returns the object; it just configures self.
What is self in Python?
The conventional name for the first parameter of an instance method, which Python passes implicitly when you call obj.method(). It's not a keyword — you could call it anything, but every Python codebase will hate you for it.
How do I run a Python script from the command line?
python script.py, or if you've made the file executable with a shebang line (#!/usr/bin/env python3) and chmod +x, just ./script.py.
What's the difference between list, tuple, set, and dict?
Lists are ordered, mutable sequences. Tuples are ordered, immutable sequences. Sets are unordered collections of unique values. Dicts are ordered (since Python 3.7) key-value mappings. Choose by what your code needs to do, not by what's shorter to type.
How do I install a package without admin rights?
Use a virtual environment (python -m venv .venv then pip install ...) or pip install --user package. For installing standalone CLI tools, pipx install package.
What's __name__ == "__main__" for?
It distinguishes "this file was executed directly" from "this file was imported as a module". The block under it runs only when you execute the file as a script, not when another module imports it.
if __name__ == "__main__":
main()How do I read environment variables in Python?
os.environ.get("VAR_NAME", "default"). For a typed config layer, use os.environ["VAR_NAME"] (raises KeyError if missing) inside a settings module that fails fast at startup.
How do I exit a Python program from code?
sys.exit(0) for success, sys.exit(1) for failure. exit() and quit() exist for the REPL but shouldn't be used in real scripts.
Hire Python engineers who know more than the syntax
Knowing the commands is the easy part. Knowing when defaultdict beats a custom setdefault, when asyncio.gather is the right concurrency tool, when to reach for numpy over a list comprehension — that's what separates an engineer who can ship Python from one who can hand it off and have it still work in two years.
Codersera matches you with vetted remote Python engineers who have shipped production data, ML, and backend systems. Each developer is technically interviewed, reference-checked, and ready to extend your engineering team — with a risk-free trial period to confirm the fit.