Module 4 · Beginner · How code works

Think like a programmer: break down problems

How to think like a programmer: understand the problem, work examples by hand, break it into small pieces, build one at a time, then test and improve.

By theprogrammers team · · 10 min read

You're given an exercise: "Write a program that reads the marks of a class and prints a report with the average, the topper, and how many students got each grade." You know variables, loops and if. You stare at the empty file and have no idea where to begin. This is the most common feeling in programming, and it isn't a knowledge problem. It's a problem-solving problem. To think like a programmer is to have a method for going from a vague task to working code.

The method is simple to describe and takes practice to use well: understand the problem, solve small examples by hand, break the task into pieces small enough to code, build and test one piece at a time, then improve. Experienced developers do this every day, often so quickly it looks like magic. This lesson walks through each step with a full worked example.

What you need first: what is an algorithm?

Key terms

  • Problem decomposition: breaking a big problem into smaller problems that are each easy to solve.
  • Requirement: something the program must do, such as "print the average".
  • Edge case: an unusual input that might break the program, such as an empty list.
  • Incremental development: writing a little code, running it, checking it, then adding more.
  • Abstraction: hiding the details of a step behind a clear name, like a function called average().
  • Pattern recognition: noticing that a new problem is like one you've solved before.

The five steps

StepQuestion to askOutput
1. UnderstandWhat exactly goes in and comes out?Clear inputs, outputs and rules
2. Work examples by handHow would I do this with pen and paper?A worked example with the right answer
3. Break it downWhat are the smaller tasks?A list of steps, each small enough to code
4. Build one piece at a timeDoes this piece work?Tested code, growing one piece at a time
5. Test and improveWhat breaks it? Can it be clearer?Correct, readable code

Here they are, applied to the class report from the opening.

Step 1: understand the problem

Before any code, pin down exactly what's wanted. Write the answers down:

  • Input: what data do we get, in what form? A list of students with their marks, for example [("Ahana", 88), ("Rohan", 52), ...].
  • Output: what should the program produce? A report with the average, the topper and a count of each grade.
  • Rules: what are the grade boundaries? Say: A for 75 and above, B for 60 to 74, C for 40 to 59, F below 40.
  • Unclear parts: two toppers with the same mark? Round the average how? An empty class?

When something is unclear in real work, you ask. In exercises, make a sensible decision and write it down: "if two students tie for top, show both; round the average to 1 decimal place".

A useful check: can you explain the task to a friend in two sentences? If not, you don't understand it well enough yet.

Step 2: solve small examples by hand

Take a tiny input and work out the answer yourself, with pen and paper:

StudentMarksGrade
Ahana88A
Rohan52C
Meera95A
Dev34F
Sara67B
  • Average: (88 + 52 + 95 + 34 + 67) ÷ 5 = 336 ÷ 5 = 67.2
  • Topper: Meera, with 95
  • Grade counts: A: 2, B: 1, C: 1, F: 1

Two benefits. First, you now know the right answer, so you can check your program later. Second, watching how you did it shows you the steps: you added the marks and divided, you scanned for the biggest, you put each student in a grade and counted.

Step 3: break it into small pieces

Write the steps as a list. If a step still feels hard to code, break it down again until each one is something you know how to write.

  1. Store the students and marks.
  2. Work out the average: - add up all the marks - divide by the number of students
  3. Find the topper: - find the highest mark - find the student or students with that mark
  4. Count the grades: - turn each mark into a grade - count how many of each grade
  5. Print the report.

Each sub-step is now tiny, and you've done most of them before. Notice step 4: "turn a mark into a grade" is a separate, reusable job. That's a sign it should be its own function.

Step 4: build one piece at a time

Don't write the whole program and then run it. Write one piece, run it, check it against your hand-worked answer, then add the next. When something breaks, you know it's in the last few lines you wrote.

Piece 1 and 2: the data and the average.

students = [("Ahana", 88), ("Rohan", 52), ("Meera", 95), ("Dev", 34), ("Sara", 67)]

total = sum(marks for name, marks in students)
average = total / len(students)
print(total, average)
336 67.2

Matches the hand calculation. On to the next piece.

Piece 3: the topper.

students = [("Ahana", 88), ("Rohan", 52), ("Meera", 95), ("Dev", 34), ("Sara", 67)]

highest = max(marks for name, marks in students)
toppers = [name for name, marks in students if marks == highest]
print(highest, toppers)
95 ['Meera']

Using a list for toppers handles ties from the start.

Piece 4: grades, as a function.

def grade(marks):
    if marks >= 75:
        return "A"
    elif marks >= 60:
        return "B"
    elif marks >= 40:
        return "C"
    else:
        return "F"

for m in [88, 75, 74, 60, 40, 39]:
    print(m, grade(m))
88 A
75 A
74 B
60 B
40 C
39 F

We tested the boundaries (75, 74, 60, 40, 39), because that's where mistakes like > instead of >= hide.

Piece 5: put it all together.

def grade(marks):
    if marks >= 75:
        return "A"
    elif marks >= 60:
        return "B"
    elif marks >= 40:
        return "C"
    else:
        return "F"

def class_report(students):
    if not students:
        return "No students in this class."
    marks_list = [marks for name, marks in students]
    average = sum(marks_list) / len(marks_list)
    highest = max(marks_list)
    toppers = [name for name, marks in students if marks == highest]
    counts = {"A": 0, "B": 0, "C": 0, "F": 0}
    for m in marks_list:
        counts[grade(m)] += 1
    lines = [
        f"Students: {len(students)}",
        f"Average: {average:.1f}",
        f"Topper: {', '.join(toppers)} ({highest})",
        "Grades: " + ", ".join(f"{g}={n}" for g, n in counts.items()),
    ]
    return "\n".join(lines)

students = [("Ahana", 88), ("Rohan", 52), ("Meera", 95), ("Dev", 34), ("Sara", 67)]
print(class_report(students))
Students: 5
Average: 67.2
Topper: Meera (95)
Grades: A=2, B=1, C=1, F=1

Every number matches the hand-worked example.

Step 5: test and improve

Now try to break it with edge cases:

def grade(marks):
    if marks >= 75:
        return "A"
    elif marks >= 60:
        return "B"
    elif marks >= 40:
        return "C"
    else:
        return "F"

def class_report(students):
    if not students:
        return "No students in this class."
    marks_list = [marks for name, marks in students]
    average = sum(marks_list) / len(marks_list)
    highest = max(marks_list)
    toppers = [name for name, marks in students if marks == highest]
    counts = {"A": 0, "B": 0, "C": 0, "F": 0}
    for m in marks_list:
        counts[grade(m)] += 1
    lines = [
        f"Students: {len(students)}",
        f"Average: {average:.1f}",
        f"Topper: {', '.join(toppers)} ({highest})",
        "Grades: " + ", ".join(f"{g}={n}" for g, n in counts.items()),
    ]
    return "\n".join(lines)

print(class_report([]))
print(class_report([("Ahana", 90), ("Kabir", 90)]))
No students in this class.
Students: 2
Average: 90.0
Topper: Ahana, Kabir (90)
Grades: A=2, B=0, C=0, F=0

The empty class and the tie both work, because we planned for them in step 1. Then improve: are the names clear? Is anything repeated? Could someone else read it? Here, splitting grade into its own function already made the code easier to test and to change; if the grade boundaries change, there's one place to edit.

Habits that help

  • Work on paper first for anything you can't picture.
  • Start with the simplest version that works, even if it's slow or ugly, then improve it.
  • Name things clearly: average_marks beats x.
  • Print often while building, to see what your variables really contain.
  • Look for patterns: "count how many of each" is the same pattern whether it's grades, words or cities.
  • When stuck, solve a smaller version: two students instead of fifty; one grade instead of four.
  • Take a break. A walk often solves what an hour of staring didn't.

Common mistakes

  • Coding before understanding, then rewriting everything when the real requirement appears.
  • Writing everything at once, then facing ten errors with no idea which line caused which.
  • Only testing the happy path, the one normal example.
  • Giving up on the whole problem instead of finishing one small piece.

Practice

  1. List the inputs, outputs and one unclear point for: "Write a program for a canteen that calculates the bill."
Show the answer

Inputs: the items ordered, their quantities and prices. Output: the total bill, maybe with an itemised list. Unclear points: is there GST or a discount? What if an item isn't on the menu? How should the total be rounded?

  1. Break this into small steps: "Find the most common word in a paragraph."
Show the answer
  1. Make the text lower-case. 2. Remove punctuation. 3. Split it into words. 4. Count each word, using a dictionary. 5. Find the word with the highest count. 6. Decide what to do about ties.
  1. Work this out by hand before coding: what's the total of the even numbers in [3, 8, 5, 12, 7, 6]? Then write the Python.
Show the answer

Even numbers: 8, 12 and 6, which add up to 26.

numbers = [3, 8, 5, 12, 7, 6]
print(sum(n for n in numbers if n % 2 == 0))
26
  1. List three edge cases to test for a function that returns the average of a list of numbers.
Show the answer

An empty list (division by zero), a list with one number, and a list with negative numbers or decimals. Very large lists are also worth one check.

  1. Change class_report so it also shows the lowest mark. Which step of the method does this belong to, and what would you test?
Show the answer

It's a new requirement (step 1) that becomes a new small piece (steps 3 and 4). Add lowest = min(marks_list) and a line f"Lowest: {lowest}" to the report. Test it with the 5-student example (lowest is 34) and with a single student, where the lowest and highest are the same.

Key takeaways

  • Understand the problem first: inputs, outputs, rules and unclear points.
  • Solve a small example by hand; it gives you the steps and the right answer to check against.
  • Break the task into pieces small enough to code, and make repeated jobs into functions.
  • Build and run one piece at a time, comparing with your hand-worked answer.
  • Test edge cases and boundaries, then improve names and structure.

Frequently asked questions

How do I get better at problem-solving in programming?

Practise regularly with problems slightly above your level, always using the steps: understand, work an example, break down, build, test. Reviewing other people's solutions after you've tried helps you collect patterns you can reuse.

What should I do when I don't know where to start?

Solve a tiny example by hand and write down what you did, in order. Those steps are your starting algorithm. Then code the first step only.

Is it cheating to look up how to do something?

No. Professional programmers look things up all day. What matters is understanding what you find and adapting it to your problem, not copying blindly.

What to learn next

  1. Write your plans down properly with pseudocode and flowcharts.
  2. Practise the method on coding problems with how to solve coding problems.
  3. Revise algorithms in what is an algorithm?