Skip to content
CodeItRaw
Basics

Lesson 3/7

You do not write 100 lines to do a thing 100 times. for repeats the work and gives you a variable that says which turn you are on.

total = 0
for i in range(1, 5):
total = total + i
# total is 10: 1 + 2 + 3 + 4
range(1, 5) gives 1, 2, 3, 4 in turn: the start is included, the end is not. To count from 1 to n you write range(1, n + 1).

The pattern for collecting a result in a loop is always the same: start a variable before the loop, update it inside, return it after. A sum starts at 0; a product starts at 1.

Tasks

Tasks open in order. Solve them all and the next lesson opens.

This lesson's tasks open when the lessons before it are finished. You can read the explanation now.Go to the current lesson

  1. 01

    From 1 to n

    Function

  2. 02

    Factorial

    Function

If you would rather not wait for the order, every problem is open without locks: Problem list