← Practice
πŸ“– Loopsloops-sum-evens
LessonΒ·difficulty 2/5Β·~12 min

Loops: sum the even numbers

Loops

A for loop walks through a sequence:

python
for x in [1, 2, 3]:
    print(x)

range(n) gives you the integers 0, 1, 2, ..., n - 1:

python
for i in range(5):
    print(i)        # prints 0 then 1 then 2 then 3 then 4

A while loop runs as long as a condition stays true.

Your task

Write a function sum_evens(n) that returns the sum of all even numbers from 0 up to (and including) n.

python
sum_evens(0)   # 0
sum_evens(2)   # 0 + 2 = 2
sum_evens(10)  # 0 + 2 + 4 + 6 + 8 + 10 = 30

If n is negative, return 0.

Tests

  • n=0 -> 0
  • n=2 -> 2
  • n=10 -> 30
  • n=11 -> 30
  • n=-3 -> 0 (hidden)
  • n=100 -> 2550 (hidden)

✦ Stuck? Ask for a spark

warming up
Loading editor…

$ Console output will appear here.

>_AI tutor
Sign in to chat with the tutor.