Most beginners learn Python one topic at a time: variables, then loops, then functions, then files. The gap appears when they try to combine them. A small, complete program shows how the pieces fit together. This guide builds one step by step: a script that totals monthly expenses from a text file, skips bad lines, and prints a summary. Every example here runs as written. The syntax is covered on the pages of the Printable Python Beginner Cheatsheet, which you can keep beside your keyboard while you follow along.
Step 1: Work with a dictionary
A dictionary holds labeled values, which suits expense data:
entries = {"rent": 1000, "food": 240, "transport": 60}
print(entries.get("gym", 0)) # 0, a safe default instead of an error
The .get() method returns a default when a key is missing. That makes lookups safer than entries["gym"], which would stop the program with an error.
Step 2: Write a function that does one job
A function should take inputs, return a result, and avoid side effects where possible. This one summarizes spending against a budget:
def monthly_summary(items, budget):
spent = sum(items.values())
return {"spent": spent, "left": budget - spent}
print(monthly_summary(entries, 1500)) # {'spent': 1300, 'left': 200}
Because the function returns a value rather than printing it, you can reuse it in other programs or test it on different data.
Step 3: Save and read a file safely
The with statement opens a file and closes it automatically, even if an error occurs:
with open("budget_notes.txt", "w") as f:
f.write("Rent paid\n")
with open("budget_notes.txt", "a") as f:
f.write("Groceries logged\n")
with open("budget_notes.txt", "r") as f:
lines = f.readlines()
print(len(lines)) # 2
Mode "w" overwrites a file, while "a" appends to it. Choose deliberately, because overwriting by accident is an easy mistake.
Step 4: Handle bad input without crashing
Real files contain typos. A conversion function that handles them gracefully is worth writing early:
def parse_amount(text):
try:
return float(text)
except ValueError:
return None
print(parse_amount("12.50"), parse_amount("abc")) # 12.5 None
Catch the specific error you expect, such as ValueError. A broad catch hides real bugs, and you want those to surface.
Step 5: Print a clear, numbered list
enumerate() gives you the position and the item together. Starting the count at 1 suits human-readable output:
for i, name in enumerate(["rent", "food"], start=1):
print(i, name)
Putting it together
A full script combines these pieces: read each line, parse the amount with the safe function, skip any line that fails, add the valid amounts to a dictionary, and pass the totals to the summary function. Each part is small enough to test on its own, which is the habit that makes larger programs manageable.
Common beginner mistakes
- Forgetting that
input()and file lines arrive as text. Convert them before doing arithmetic. - Using
"w"when you meant"a", which erases the file. - Catching every exception with a bare
except, which hides mistakes.
Where to go next
Once this script works, add a loop that asks the user for entries, or save the summary to a new file. The next topics to study are lists versus dictionaries, which we compare in our data structures guide, and the basics covered in the beginner syntax guide.
Testing your script before you trust it
A script that appears to work on one example may fail on another. Before you rely on a program, test it with several inputs, including ordinary values, empty files, lines with errors and very large numbers. Each test should have a predicted result written down before you run it. When the actual output differs, the gap shows you where your assumptions were wrong. This discipline feels slow at first, but it saves hours of debugging later, because you catch errors while the code is still small.
Print statements remain a perfectly good debugging tool at this stage. Printing the value of a variable at a key point shows you exactly what the program is doing, and removing the prints once the logic is correct keeps the final script clean.
Extending the script step by step
Once the basic script works, extend it one feature at a time. You might add a function that writes the summary to a new file, or a loop that lets the user enter expenses from the keyboard. Each change should be small enough that you can test it immediately. When something breaks, you know the cause is in the last change, which makes the problem easy to find. Large rewrites, by contrast, hide errors inside many changes at once.
Organising the file for someone else to read
Even a short script benefits from clear organisation. Put the functions at the top, use names that describe what each variable holds, and add a brief comment where the logic is not obvious. Your future self will read the script months later, and a clear layout makes that reading quick. Clean code is also the easiest kind to share with a colleague or post for feedback.
Where this project leads
A finished budget summary script is a real piece of software. It reads data, handles errors, applies functions and produces output, which are the same skills used in far larger systems. The step from here is not to learn an entirely new language but to apply these habits to new problems. Choose the next small project, repeat the cycle of planning, testing and extending, and the skills compound.
Choosing names that explain the code
Good names do much of the documenting for you. A variable called total_spent communicates its purpose far better than a single letter, and a function called parse_amount says what it does. Spend a few moments choosing names before you write the code. The effort pays back every time you read the script later, and it makes the program easier for a collaborator to understand.
Reading the script aloud as a final check
Before calling a script finished, read it aloud from top to bottom, explaining each step as you go. Gaps in your understanding become obvious when you have to say them out loud. You may notice a variable that is never used, a condition that can never be true or a comment that no longer matches the code. This quick review catches problems that automated tools sometimes miss, and it reinforces what the program actually does.
Explore the collection
The Printable Python Beginner Cheatsheet keeps these patterns on four printable pages. Browse the wider cheatsheets category, or see all planners for study routines.
