0%
Checking the code runner…

Instructions

Lesson 3 of 4

Loops

Loops repeat code so you don't have to. A for loop runs once for each item in a sequence. range(3) gives you 0, 1, 2:

Try changing the range. range(1, 6) starts at 1 and stops before 6.

Building up a total

A common pattern is to start a variable at zero and add to it inside the loop:

while loops

A while loop keeps going as long as its condition is true:

Careful: if the condition never becomes false, the loop runs forever. Here that just means the sandbox stops it after a few seconds.

Exercise: Sum to N

Write sum_to(n) that returns 1 + 2 + ... + n.

Your turn!

Write your code in and press Submit answer.

  • print(sum_to(3)) → 6
  • print(sum_to(10)) → 55
  • plus 2 hidden checks

Help

Hint

Start with total = 0, loop over range(1, n + 1), add each number to total, then return total.

Pass the exercise to complete this lesson.

Terminal
Press Run to see your output here.