Breaking Problems into Steps
Concepts covered: Functions
Decomposition means breaking a big problem into smaller pieces you can solve one at a time. Most hard problems turn out to be a collection of simple ones.
Example: calculating a tip
Problem: Write a program that calculates the tip for a restaurant bill.
Written out as steps first, it looks like this:
- Get bill amount: Collect the total bill as input from the user
- Get tip percent: Collect the desired tip percentage
- Calculate tip: Multiply bill by percentage divided by 100
- Calculate total: Add the tip amount to the original bill
- Display results: Print the tip and total for the user
Now each step is simple enough to code directly:
bill = 85.50
tip_percent = 18
tip_amount = bill * tip_percent / 100
total = bill + tip_amount
print(f"Tip: ${tip_amount:.2f}")
print(f"Total: ${total:.2f}")Output:
Tip: $15.39 Total: $100.89
Each line of the code maps to one of the steps above, because the steps were written first.
Writing pseudocode first
Pseudocode is a way of writing out your solution in plain language before converting it to real code. It helps you focus on logic without worrying about syntax.
- Pseudocode
- FOR each number in the list
- IF number is even
- add it to the sum
- PRINT the sum
- Python
- for num in numbers:
- if num % 2 == 0:
- total += num
- print(total)
Write pseudocode in whatever notation feels natural; it only has to be clear to you, not formal. If you can follow your pseudocode, you can convert it to Python.
The habit that pays off most is decomposing a problem into plain-English steps before writing code. Once you can narrate each step, turning it into code is mostly transcription.
Pseudocode has no syntax to get right, so write it in whatever form makes the logic of the algorithm obvious to you.
About this lesson
This section is part of the Problem Solving: Beginner lesson on DataDriven, the home of data engineering. Lessons cover SQL, Python, Spark, data modeling and pipeline architecture, and each section pairs its explanation with worked examples and practice you run as you go.