For Statements

By HyperNeutrino
Written 19 days ago

The for statement is used to loop a block of code through a list. The basic syntax is this:

for element in collection:

This will print each element in the collection line-by-line.

Inside the code block, you can refer to the variable name defined as the loop iterator which is the corresponding element on each iteration.

This can be paired with range to easily loop from one number to another. The range function takes one to three parameters.

range(x) => [0, 1, 2, ..., x - 1]
range(x, y) => [x, x + 1, x + 2, ..., y - 1]
range(x, y, z) => [x, x + z, x + 2z, ..., up to y] # not including y

So, if one wished to loop from 1 through 10, this for loop would do the trick:

for i in range(1, 11):