Python gets easier with short, deliberate practice. Small exercises teach more than Python programming basics because they require you to decide what a program should do, check whether it does it, and correct it when it responds unexpectedly.
Set Up a Practice Routine That Makes Small Python Exercises Useful
Treat each exercise as a short cycle: understand the problem, make a first attempt, test it, and then improve it. The point is not to produce perfect code immediately. It is to develop the habit of turning an unclear task into instructions that work.
Keep every exercise in its own Python file, or use a clear heading to separate exercises in a notebook. This makes older work easier to revisit and gives you a visible record of how your approach has developed.
-
Read the prompt without coding yet.
Work out what information the program receives, what it needs to produce, and which rules apply. For a receipt-total exercise, ask whether tax is included, whether a discount can apply, and how the total should appear.
-
Write a few example cases by hand.
Before coding, create a small set of inputs and expected outputs. These examples give you something specific to test against.
For a prompt such as “calculate the total price of items,” your cases might be:
- No items: The total should be
0. - One item costing
12.50: The total should be12.50. - Three items costing
5,10, and2.25: The total should be17.25. - A non-number entered as a price: The program should not silently treat it as a valid amount.
- No items: The total should be
-
Write the simplest version that can work.
Leave extra features for later. Begin with the main calculation or rule. A short, straightforward solution is easier to test than a larger program carrying several incomplete ideas.
-
Test normal cases and awkward cases.
Check values at the edges of the problem: zero, empty text, exact boundaries, negative numbers, and unusually large values. These tests expose assumptions you may not have noticed.
-
Use errors as clues.
Start near the bottom of an error message. The last line generally identifies the exception and gives its message; the traceback above it points to the relevant file and line. When necessary, add temporary
print()statements to inspect a value or confirm that a branch runs.
A program that stops with a clear error is often closer to correct than one that runs while quietly producing the wrong answer. At least the first program is telling you where to look.
Real story
I once spent 20 minutes debugging a beginner Python loop only to realize I’d named the variable `sum` and then tried to call `sum()` five lines later. My terminal was full of errors, my coffee was cold, and I was still confidently staring at the screen like the problem had to be the computer. It was not the computer.
Have a story of your own? Share it in the comments below.
Begin With Input, Output, and Simple Calculations
Begin with exercises that follow a complete path: receive a value, transform it, and display a result. These programs are small enough to grasp quickly while still reinforcing the basic concepts of computer programming: input conversion, calculation, and readable output.
Good early exercises include:
- A temperature converter from Celsius to Fahrenheit
- A distance converter from kilometers to miles
- A tip calculator
- A receipt-total calculator
- A bill splitter
- A savings goal calculator
Example: Split a Bill Between Several People
This exercise takes a bill amount, adds a tip, and divides the result among the specified number of people. It covers numeric input, arithmetic, named values, and formatted output.
bill = float(input("Bill amount: "))
tip_percent = float(input("Tip percentage: "))
people = int(input("Number of people: "))
tip_amount = bill * (tip_percent / 100)
total = bill + tip_amount
if people > 0:
amount_per_person = total / people
print(f"Each person pays ${amount_per_person:.2f}")
else:
print("The number of people must be at least 1.")
Run the program with a bill of 60, a tip of 15, and 3 people. Then try one person, no tip, and zero people.
The zero-people test is important because division by zero raises an error. Checking for it is more than defensive programming: it defines how the program should respond when the input is not meaningful.
Ways to Extend the Exercise
After the basic version works, make one change at a time:
- Ask whether the bill already includes tax.
- Round the final amount up to the nearest whole currency unit.
- Let the user enter a fixed tip amount instead of a percentage.
- Display the subtotal, tip amount, total, and per-person cost.
- Reject negative bill amounts.
Keep the original working version. If an extension breaks the program, comparing the two versions makes it easier to identify the change that caused the problem.
Practice Decisions With Rules, Conditions, and Boundary Cases
Many programs need to make decisions: approve or reject an application, classify a score, apply a pricing rule, or select a menu option. These exercises turn written rules into conditions Python can evaluate.
Start with one clear rule and add complexity later. A shipping calculator, for example, might begin with “orders of 50 or more ship free.” You can then add a lower fee for medium-sized orders and a higher fee for small ones.
Example: Build a Shipping-Cost Calculator
Suppose the rules are:
- Orders of
50or more have free shipping. - Orders from
25up to, but not including,50have shipping of4.99. - Smaller orders have shipping of
7.99.
order_total = float(input("Order total: "))
if order_total < 0:
print("Order total cannot be negative.")
elif order_total >= 50:
shipping_cost = 0
print(f"Shipping: ${shipping_cost:.2f}")
elif order_total >= 25:
shipping_cost = 4.99
print(f"Shipping: ${shipping_cost:.2f}")
else:
shipping_cost = 7.99
print(f"Shipping: ${shipping_cost:.2f}")
Test the exact points where the rules change:
Order total: 24.99 -> Shipping: $7.99
Order total: 25.00 -> Shipping: $4.99
Order total: 49.99 -> Shipping: $4.99
Order total: 50.00 -> Shipping: $0.00
If you test only 10, 30, and 100, the program may appear correct while still mishandling boundary values.
Decision Exercises to Try Next
Build each exercise in stages rather than attempting every rule at once.
- Grade classifier: Convert a numeric score into a letter grade. Test scores exactly at each grade boundary.
- Eligibility checker: Decide whether someone meets age and membership requirements for an activity.
- Password rule checker: Check whether text is long enough and contains required characters.
- Text-based menu: Let the user choose an action, such as viewing a balance, adding money, or quitting.
- Simple discount calculator: Apply a discount only when an order reaches a defined minimum.
For each condition, ask, “What happens when this is true?” and “What happens when it is false?” Then ask, “What happens exactly at the limit?”
Use Repetition to Process Lists and Build Interactive Exercises
Loops allow a program to process multiple values without duplicating the same code. Begin with a for loop over a list when the number of items is known. After that, try while loops for programs that continue until the user decides to stop.
A useful loop should track something as it runs: a total, count, smallest value, largest value, or number of matches. This gives the repetition a purpose beyond printing each item.
Example: Analyze a List of Numbers
This program counts positive values and calculates an average. It also handles an empty list without failing.
numbers = [8, -2, 0, 14, 5]
total = 0
positive_count = 0
for number in numbers:
total += number
if number > 0:
positive_count += 1
if len(numbers) > 0:
average = total / len(numbers)
print(f"Average: {average:.2f}")
else:
print("No numbers were provided.")
print(f"Positive values: {positive_count}")
Try replacing the list with:
[]
[0, 0, 0]
[-5, -1, -8]
[4, 9, 12]
The empty-list test is particularly useful. An average requires division by the number of values, and an empty list provides no values for that calculation.
Practice Tracking Values Inside a Loop
Using the same list of numbers, add one feature at a time:
- Count how many values are negative.
- Find the largest value.
- Find the smallest value.
- Count how many values are even.
- Print only values greater than a chosen limit.
- Calculate the sum of values above zero.
For minimum and maximum exercises, decide what an empty list should mean before writing the code. With no numbers present, there is no smallest value to find.
Move to User-Controlled Repetition
A while loop fits situations where the user determines how many times the program repeats. A simple menu is a practical exercise because it brings together input, decisions, and repetition.
choice = ""
while choice != "q":
print("\nOptions: a = add, q = quit")
choice = input("Choose an option: ").lower()
if choice == "a":
print("You chose add.")
elif choice == "q":
print("Goodbye.")
else:
print("That option is not available.")
Extend it gradually. You might keep a running total when the user selects a, or add another option that displays the current total.
Organize Repeated Logic Into Functions and Small Tests
When the same calculation or rule appears more than once, move it into a function. A function names the task, avoids duplicated code, and makes testing with known values more straightforward.
Keep each function focused. A function called calculate_tip() should calculate and return a tip. It does not also need to request input, print a receipt, and decide who washes the dishes.
-
Find a repeated or self-contained task.
In a bill program, possible tasks include calculating the subtotal, tip, and cost per person.
-
Write a function with clear parameters.
Parameters specify the information the function needs. Choose names that make those values clear.
-
Return the result instead of printing it inside the function.
A returned value can be used in several ways. You can print it, compare it, round it, or test it.
-
Test the function with simple known inputs.
Check ordinary values, zero values, and invalid cases where appropriate. Testing individual pieces is generally simpler than testing an entire program at once.
-
Use the tested functions in the larger program.
Keep input and output near the main part of the program, and let the functions handle the calculations.
Example: Refactor a Bill Calculator
def calculate_tip(subtotal, tip_percent):
return subtotal * (tip_percent / 100)
def calculate_total(subtotal, tip_amount):
return subtotal + tip_amount
def cost_per_person(total, people):
if people <= 0:
return None
return total / people
subtotal = 80
tip = calculate_tip(subtotal, 15)
total = calculate_total(subtotal, tip)
share = cost_per_person(total, 4)
print(f"Tip: ${tip:.2f}")
print(f"Total: ${total:.2f}")
print(f"Each person pays: ${share:.2f}")
You can test the functions directly with assert statements:
assert calculate_tip(100, 10) == 10
assert calculate_total(50, 5) == 55
assert cost_per_person(60, 3) == 20
assert cost_per_person(60, 0) is None
During normal execution, a failed assert raises AssertionError. Assertions work well for simple development checks, but they are not a guaranteed runtime validation method because Python can omit them when run with the -O optimization option.
Useful function exercises include reusable temperature conversions, calculator operations, text-cleaning rules, and score classifiers. Keep the functions limited to one clear job.
Combine the Skills in a Small Python Practice Project
A small project gives the separate exercises a shared purpose. Choose something that fits in one file and can grow in stages, such as a quiz, expense tracker, contact list, or number-guessing game.
A text-based quiz makes a solid first project because it uses stored data, loops, conditions, functions, score tracking, and a clear ending. It can be useful before it has many features.
-
Write a short plan before coding.
Decide what the program asks, what data it stores, how it tracks progress, and how it ends. For a quiz, you need questions, correct answers, a score, and a final summary.
-
Store a few questions in a simple structure.
Begin with two or three questions. A list of tuples is sufficient for a beginner practice project.
questions = [ ("What is 2 + 2? ", "4"), ("What keyword starts a function in Python? ", "def"), ("What does len() return for a string? ", "length"), ] -
Loop through the questions and check answers.
Keep the comparison simple at first. Using
.strip().lower()removes leading and trailing whitespace and makes capitalization less important when matching answers.score = 0 for question, correct_answer in questions: answer = input(question).strip().lower() if answer == correct_answer: print("Correct.") score += 1 else: print(f"Not quite. The answer was {correct_answer}.") -
Show a result at the end.
Include both the score and the number of questions so the output is clear.
print(f"\nFinal score: {score} out of {len(questions)}") -
Add one improvement after the first version works.
Pick one feature instead of rebuilding the project all at once. You could add a replay option, show a percentage score, reject blank answers, randomize question order later, or group questions by topic.
-
Review the finished program.
Read it as a new user would. Check that variable names are clear, repeated code could become a function, invalid input receives a sensible response, and each prompt explains what the user should do.
The project does not need a long list of features to be worthwhile. A small program that you planned, tested, and improved teaches the central skill behind Python practice: breaking a problem into steps a computer can follow.



