← All guides

Programmer’s Reference

Python

Write small scripts, process data, and inspect systems safely.

Python 3.9+ examples unless stated otherwise. Use a virtual environment for project dependencies.

26 entries · Essentials first · Reviewed October 5, 2026

Glossary: commands, keywords & terms

Select a term for its definition, syntax, example, and common mistakes.

Keywords and syntax

if / elif / else

Execute the first branch whose condition is true.

Python code
count = 3
if count > 5:
    print('Many')
elif count > 0:
    print('Some')
else:
    print('None')

Practical useUse this construct in your own practice project.

Common mistakesUse a colon and consistent indentation; Python uses elif, not elseif.

Source: docs.python.org documentation

or

Return the first truthy operand, or the last operand if neither is truthy.

Python code
nickname = ''
name = nickname or 'Guest'
print(name)

Practical useUse this construct in your own practice project.

Common mistakesor returns an operand, not necessarily a bool; falsey values include 0 and empty collections.

Source: docs.python.org documentation

and

Return the first falsey operand, or the last operand; short-circuit evaluation applies.

Python code
ready = True
allowed = False
if ready and allowed:
    print('Proceed')

Practical useUse this construct in your own practice project.

Common mistakesUse and for boolean logic; & is a different operator.

Source: docs.python.org documentation

not

Return the boolean negation of a value.

Python code
ready = False
if not ready:
    print('Waiting')

Practical useUse this construct in your own practice project.

Common mistakesPython uses not, not !.

Source: docs.python.org documentation

for / in / range

Iterate through an iterable; range supplies a sequence of integers.

Python code
for number in range(3):
    print(number)

Practical useUse this construct in your own practice project.

Common mistakesrange(3) yields 0, 1, 2; its stop value is excluded.

Source: docs.python.org documentation

while

Repeat while a condition is true.

Python code
attempt = 0
while attempt < 3:
    attempt += 1
    print(attempt)

Practical useUse this construct in your own practice project.

Common mistakesUpdate the condition or provide an exit path.

Source: docs.python.org documentation

break

Exit the innermost loop immediately.

Python code
for n in range(5):
    if n == 2:
        break
    print(n)

Practical useUse this construct in your own practice project.

Common mistakesA loop else clause is skipped when break exits the loop.

Source: docs.python.org documentation

continue

Skip the remaining body of the current iteration.

Python code
for n in range(3):
    if n == 1:
        continue
    print(n)

Practical useUse this construct in your own practice project.

Common mistakesIn a while loop, ensure updates happen before a continue that would skip them.

Source: docs.python.org documentation

def / return

Define a function and return a result.

Python code
def double_value(number):
    return number * 2

print(double_value(3))

Practical useUse this construct in your own practice project.

Common mistakesA function without an explicit return returns None.

Source: docs.python.org documentation

pass

Provide an intentionally empty statement where a block is required.

Python code
def unfinished_example():
    pass

Practical useUse this construct in your own practice project.

Common mistakespass does nothing; it is not the same as continue.

Source: docs.python.org documentation

in / not in

Test membership in a container.

Python code
allowed = ['read', 'write']
print('read' in allowed)
print('delete' not in allowed)

Practical useUse this construct in your own practice project.

Common mistakesMembership in a dictionary checks keys, not values.

Source: docs.python.org documentation

try / except / finally / raise

Handle exceptions and run cleanup.

Python code
try:
    raise ValueError('Demo')
except ValueError:
    print('Handled')
finally:
    print('Cleanup')

Practical useUse this construct in your own practice project.

Common mistakesCatch specific expected exceptions; avoid suppressing all errors.

Source: docs.python.org documentation

with / as

Use a context manager to handle setup and cleanup.

Python code
from contextlib import nullcontext
with nullcontext('Demo') as value:
    print(value)

Practical useUse this construct in your own practice project.

Common mistakesThe object must support the context-manager protocol.

Source: docs.python.org documentation

import / from / as

Load a module or selected names, optionally using an alias.

Python code
import math as maths
from pathlib import Path
print(maths.sqrt(9))
print(Path('demo.txt').name)

Practical useUse this construct in your own practice project.

Common mistakesDo not name your own file after a standard module you intend to import.

Source: docs.python.org documentation

goto (not supported)

Python has no goto keyword. Use structured branches, loops, functions, and return.

Python code
def describe(ready):
    if ready:
        return 'Ready'
    return 'Waiting'

print(describe(True))

Practical useUse this construct in your own practice project.

Common mistakesWriting goto or a label is not valid Python control-flow syntax.

Source: docs.python.org documentation

Essentials

Lists, dictionaries, and loops

Store records in a list of dictionaries, then iterate and access named fields.

Python code
sites = [{'name': 'Demo', 'enabled': True}]
for site in sites:
    if site['enabled']:
        print(site['name'])

Practical useProcess a sanitized site inventory.

Common mistakesUse True and False with capitals; missing dictionary keys raise KeyError.

Source: docs.python.org documentation

Functions and exceptions

Use a function to convert input and handle the expected conversion error.

Python code
def parse_port(text):
    port = int(text)
    if not 1 <= port <= 65535:
        raise ValueError('Port out of range')
    return port

try:
    print(parse_port('8080'))
except ValueError as error:
    print(error)

Practical useValidate a demo service port before storing it.

Common mistakesAvoid a bare except; it can hide unrelated failures. Do not print private exception details in a public API.

Source: docs.python.org documentation

Project setup

Create a virtual environment

Create an isolated environment and install packages through its interpreter.

Terminal
python3 -m venv .venv
source .venv/bin/activate
python -m pip --version

Practical useKeep project development tools separate from the operating system.

Common mistakesActivation syntax differs on Windows. Do not commit .venv; avoid sudo pip installs into system Python.

Source: docs.python.org documentation

Files and data

Read text with pathlib

Read a fixed UTF-8 fixture through a Path object.

Python code
from pathlib import Path
path = Path('demo-status.txt')
text = path.read_text(encoding='utf-8')
print(text)

Practical useRead a local staging status fixture.

Common mistakesA relative path starts at the current working directory. Check trusted paths and handle missing files.

Source: docs.python.org documentation

Parse and format JSON

Convert JSON text to a Python value and serialize it for readable output.

Python code
import json
status = json.loads('{"running": true}')
print(json.dumps(status, indent=2))

Practical useInspect a sanitized backend fixture.

Common mistakesJSON uses true/null; Python uses True/None. Validate the expected structure after parsing.

Source: docs.python.org documentation

Write a fixture file

Write UTF-8 text to a fixed file. Existing contents at that path are replaced.

⚠ Caution: Replaces existing file contents.

Python code
from pathlib import Path
Path('demo-output.txt').write_text('Check complete\n', encoding='utf-8')

Practical useSave a disposable staging report, never a live application configuration.

Common mistakeswrite_text overwrites the target. Confirm the directory and filename first.

Source: docs.python.org documentation

System scripts

Run a command without a shell

Pass arguments as a list, capture output, and enforce a timeout.

Python code
import subprocess
result = subprocess.run(
    ['git', 'status', '--short'],
    check=True, capture_output=True, text=True, timeout=10
)
print(result.stdout)

Practical useCheck a staging checkout through a fixed allowed command.

Common mistakesAvoid shell=True with untrusted input. Catch timeout and nonzero-exit errors when the application must recover.

Source: docs.python.org documentation

Record application events

Configure logging and emit an informational event with a substituted field.

Python code
import logging
logging.basicConfig(level=logging.INFO, format='%(levelname)s %(message)s')
logging.info('Checked service %s', 'demo')

Practical useRecord the result category of a health check.

Common mistakesNever log passwords, tokens, email contents, or private connection strings.

Source: docs.python.org documentation

Back to top ↑