~/learn/Python · Fundamentals

Mini-project: sum the even numbers

Combine variables, conditions and loops, then package the result for your first free practice question.

10 min readlesson 8 of 23mini-projectdefreturneven numbers

why this matters

This small project connects each concept to a real, free practice question, including the function signature its checks expect.

Your task is to add only the even numbers in a list. An even whole number is divisible by 2 with no remainder, so number % 2 == 0 is the test. For [1, 2, 3, 4], keep 2 and 4 and add them to get 6. An empty list should give 0.

python · editable
loading editor…

Try it: Try [-2, -3, 7, 4]. The even numbers are -2 and 4, so the result should be 2.

Why the indentation matters

for each number:
    if it is even:
        add it to total
print after the loop → display one final result

A function packages instructions so they can be reused with different inputs. def starts the definition, sum_evens is the chosen name, and nums is a parameter: the name used for the input inside the function. Defining the function does not run its body; sum_evens([1, 2, 3, 4]) calls it with that list.

return hands the result back to the caller. print only displays it. The practice question needs a returned number so its checks can compare your answer. Keep return after the loop, inside the function: returning inside the loop would stop too early.

python · editable
loading editor…

Try it: Call the function with [2, 4, 6], [1, 3, 5] and [-2, 4]. Predict 12, 0 and 2.

Expected output

6
0

Test several inputs, not just the example. Empty input checks that the initial total works. All-odd input checks that nothing unwanted is added. Negative even numbers check that the condition is about divisibility, not whether a number is positive.

python · editable
loading editor…

Try it: Add a test for a single even number and a single odd number.

You now have the building blocks for your first Python practice question. Try writing sum_evens again from the starter code rather than copying it. Then continue to Collections for lists and dictionaries, and Functions for defaults, scope and reusable logic.

key takeaways

  • number % 2 == 0 identifies even whole numbers, including negative ones.
  • Keep the running total outside the loop and the addition inside the condition.
  • def defines a reusable function; calling it runs the body.
  • return sends the result back; keep it after the loop.
  • Check empty, all-odd, negative and single-value inputs.

check your understanding

Why should return total be after the for loop, rather than inside it?

free practice

Build confidence with a question you can solve without Pro.