Python · Stage 10 – Beyond the Basics · Lesson 50 of 50

Security-Conscious Coding Habits

Build safe habits around input, secrets, dependencies, files, and permissions.

Validate input by checking its type, allowed range, length, and format before using it.

port = int(port_text)
if not 1 <= port <= 65535:
    raise ValueError("Port out of range")
Line-by-line explanation
  1. Text is converted into an integer.
  2. The condition rejects values outside valid port boundaries.
  3. A clear exception stops unsafe use.
import os
api_key = os.environ["API_KEY"]
Line-by-line explanation
  1. The os module is imported.
  2. os.environ reads environment variables.
  3. The secret is supplied outside the source file.

Use trusted dependencies, keep them updated, avoid shell commands built from user input, restrict file paths, use least privilege, and never test systems without permission.