Contact, if you are interested in this website / domain name / Sponsorship / Advertisement / Partnership
HomeLearnToolsRoadmapVideosBuildSponsorshipAboutContactStart a project
Beginner

Python Basics: First Script to Automation

11 minute read · Last updated 2026-10-31 · Written and reviewed by the Code.House editorial team

Python's appeal is that a useful script is short. This guide moves quickly through the syntax and spends its time on the parts that make scripts actually useful: data structures, files, errors and environments.

Values and collections

name = "Ada"            # str
count = 42              # int
rate = 0.075            # float
active = True           # bool

prices = [10, 25, 40]                    # list — ordered, changeable
point = (12.5, 48.2)                     # tuple — ordered, fixed
tags = {"python", "automation"}          # set — unique, unordered
user = {"name": "Ada", "role": "admin"}  # dict — key/value

Dictionaries are the workhorse. Reading a key that does not exist raises KeyError, so use user.get("email", "") when a value is optional.

List comprehensions replace most short loops and read cleanly once they are familiar:

totals = [p * 1.13 for p in prices if p > 15]

Control flow and functions

def tax_total(prices, rate=0.13):
    """Return the sum of prices with tax applied."""
    return round(sum(p * (1 + rate) for p in prices), 2)

for price in prices:
    if price > 30:
        print(f"{price} is above the threshold")
    elif price == 30:
        print("exactly at the threshold")
    else:
        print(f"{price} is below")

Indentation is syntax, not style — four spaces per level, consistently. F-strings (f"{value}") are the current way to build strings and handle formatting too: f"{total:,.2f}" gives thousands separators and two decimals.

Files and data

Reading and writing files uses a context manager, which closes the file even if something fails:

from pathlib import Path
import csv, json

text = Path("notes.txt").read_text(encoding="utf-8")

with open("report.csv", newline="", encoding="utf-8") as fh:
    for row in csv.DictReader(fh):
        print(row["customer"], row["amount"])

Path("output.json").write_text(json.dumps({"ok": True}, indent=2), encoding="utf-8")

Always pass encoding="utf-8". The default differs between operating systems, and that difference is behind a large share of "works on my machine" bugs involving accented characters.

Handling errors deliberately

try:
    value = int(user_input)
except ValueError:
    print("That was not a whole number.")
    value = 0
finally:
    print("Done.")

Catch the specific exception you expect. A bare except: swallows everything, including the keyboard interrupt you press to stop a runaway script, and hides real bugs behind a generic message.

Virtual environments and packages

Installing libraries globally eventually produces two projects that need different versions of the same package. A virtual environment keeps each project's dependencies separate.

python -m venv .venv
source .venv/bin/activate        # Windows: .venv\Scripts\activate
pip install requests pandas
pip freeze > requirements.txt

Commit requirements.txt, never the .venv folder. Anyone cloning the project recreates the environment with pip install -r requirements.txt.

A first useful script

This pattern — read files, transform, write a summary — covers a surprising number of real tasks.

from pathlib import Path
import csv
from collections import defaultdict

totals = defaultdict(float)

for path in Path("exports").glob("*.csv"):
    with path.open(newline="", encoding="utf-8") as fh:
        for row in csv.DictReader(fh):
            totals[row["category"]] += float(row["amount"])

with open("summary.csv", "w", newline="", encoding="utf-8") as fh:
    writer = csv.writer(fh)
    writer.writerow(["category", "total"])
    for category, amount in sorted(totals.items(), key=lambda x: -x[1]):
        writer.writerow([category, round(amount, 2)])

print(f"Wrote {len(totals)} categories.")

Common questions

Python 3.12, 3.13 or newer?

Use the newest version your libraries support. Differences between recent releases rarely affect beginner code, and newer versions bring better error messages.

When should I use a class?

When data and the functions that operate on it keep travelling together. Until then, functions plus dictionaries are simpler and easier to test.

Keep reading

Spotted something out of date? Send a correction — guides are revised rather than quietly deleted.