Python is an interpreted, object-oriented, high-level language with dynamic typing and readable syntax, available free for Windows, macOS, and Linux under an OSI-approved open-source license. Version 3.x is the current default; the 3.15 documentation series is the active reference line. Install the latest stable 3.x build unless a project pins an older interpreter.

# hello.py — save, then run: python hello.py
def greet(name: str = "world") -> str:
    return f"Hello, {name}!"

if __name__ == "__main__":
    print(greet())
    print(greet("Python"))
Construct Syntax Purpose
Variable x = 42 Names bind objects; no type declaration
Function def f(a, b=1): Default args; return optional
List / Dict [1, 2], {"k": 1} Built-in ordered/v indexed containers
Comprehension [n*n for n in range(5)] Inline loop-and-build
Import import math / from os import path Standard library or packages
Context manager with open("f.txt") as fh: Guaranteed cleanup

Install Python and Run Your First Script

  1. Download the installer from the official site's download page; on Windows, keep Add python.exe to PATH checked before clicking Install Now.
  2. On macOS, use the official .pkg installer rather than the bundled system interpreter, which lags behind current releases.
  3. Confirm with python --version (Windows) or python3 --version (macOS/Linux); a version string means the interpreter is on your path.
  4. Create the file above as hello.py and run python hello.py. If you see command not found or Python was not found, the PATH entry is missing—re-run the installer and pick Modify.
  5. Install third-party packages through pip: python -m pip install --upgrade pip then python -m pip install requests.

Use python -m pip rather than bare pip so the installer targets the same interpreter that runs your scripts—mixed installs are a common source of "module not found" errors.

Worked Example: Parse a CSV with the Standard Library

Assume sales.csv sits in the same folder with a header row region,units,price and three data rows starting on line 2. This reads each row, computes revenue, and prints a total.

import csv

total = 0.0
with open("sales.csv", newline="", encoding="utf-8") as fh:
    for row in csv.DictReader(fh):
        total += int(row["units"]) * float(row["price"])

print(f"Total revenue: {total:.2f}")

DictReader maps header names to values, so reordering columns in the source file won't break the code. If the file uses a different delimiter, pass delimiter=";" to csv.DictReader. A FileNotFoundError means the working directory differs from the script's folder—run from the same terminal directory or use an absolute path. If you spot UnicodeDecodeError, change encoding="utf-8" to the file's real encoding (often cp1252 on legacy Windows exports).

Worked Example: A Function, Loop, and Conditional Together

Start with scores = [88, 72, 95, 61] on line 1. The code below returns letter grades and a pass count.

scores = [88, 72, 95, 61]

def grade(score: int) -> str:
    if score >= 90:
        return "A"
    if score >= 80:
        return "B"
    if score >= 70:
        return "C"
    return "F"

for s in scores:
    print(s, grade(s))

passed = sum(1 for s in scores if s >= 70)
print(f"Passed: {passed} of {len(scores)}")

The sum(... for ... if ...) pattern is a generator expression—no list is built in memory. Indentation defines blocks in Python; mixing tabs and spaces raises TabError, so configure your editor to insert four spaces.

Worked Example: Object-Oriented Class with Methods

Classes bundle data and behavior. This example models a counter that only increments in whole steps.

class Counter:
    def __init__(self, start: int = 0) -> None:
        self.value = start

    def tick(self, step: int = 1) -> None:
        if step < 1:
            raise ValueError("step must be positive")
        self.value += step

c = Counter()
c.tick()
c.tick(5)
print(c.value)  # 6

__init__ runs on every construction; self refers to the instance. Raising ValueError on a bad step is preferable to silently ignoring input—callers can catch it with try/except ValueError. Python uses dynamic binding, so you can add attributes at runtime, but explicit __init__ fields make code easier to debug.

Troubleshoot Common Python Errors

Error Typical cause Verified fix
SyntaxError: invalid syntax Missing colon, unbalanced parens, or = where == was intended Read the caret location; check the line above too
IndentationError / TabError Mixed tabs and spaces, or inconsistent nesting Convert all tabs to four spaces; confirm block alignment
NameError: name 'x' is not defined Variable used before assignment or outside its scope Define before use; pass into the function or return it
ModuleNotFoundError Package not installed into the active interpreter python -m pip install <package> using the same interpreter as python
FileNotFoundError Wrong working directory or mistyped filename Print os.getcwd(); use an absolute path or pathlib.Path
TypeError: ... takes N positional arguments Wrong argument count or missing self Check the def signature; pass keyword arguments when unclear
ValueError: invalid literal for int() Passing non-numeric text to int() Trim whitespace with .strip(), or validate with .isdigit() first

Frequently Asked Questions

Do I need to install anything to start learning Python?

No—several browser-based interpreters run Python with no install, but for real files, pip packages, and IDEs you should install the official 3.x build from python.org. The current documentation index at docs.python.org covers both setup and the tutorial.

What is the difference between Python 2 and Python 3?

Python 3 is the supported line; Python 2 reached end-of-life and should only appear in legacy maintenance work. New code should target the newest stable 3.x release, which is the 3.15 documentation series at the time of writing. The language reference at docs.python.org/3/reference documents syntax and semantics exactly.

Where do I find the standard library documentation?

The standard library reference lists every bundled module with examples—file I/O, csv, json, datetime, re, pathlib, and hundreds more—so check it before installing a third-party package. The official reference sits at docs.python.org/3/library Python standard library.

How do I run a script from the command line on Windows versus macOS?

On Windows use python script.py from the folder containing the file, or py script.py if the launcher is installed. On macOS and Linux use python3 script.py. If neither resolves, the PATH is misconfigured; re-run the installer and enable the PATH option rather than editing PATH by hand.