Week 1: for loops, lists, and range

Loops

Loops allow us to repeat a series of commands multiple times.

The syntax of a for loop in python is:

for <variable> in <sequence>:
   <statement1>
   <statement2>
   ...

The semantics of a for loop is that the <variable> will be assigned to the first item in the sequence and then the indented statements will be executed in order. Then the <variable> will be assigned to the next item in the sequence and the indented statements will be executed in order again. And so on, until the end of the sequence is reached.

Sequences

A sequence is a collection of items. One way to create a sequence is to make a list. Below are some examples of lists (the last one is the empty list).

["apple", "banana", "cherry"]
[10, 20, 30, 40, 50]
[]

A list is a type in python (like int, float, and str).

We can use lists in for loops:

for number in [5, 4, 3, 2, 1]:
   print(number)
print("Blast off!")

But writing lists by hand is too cumbersome. We want a way to easily create long sequences.

Generating sequences with range

Rather than writing out a sequence by hand, we can use the range command to generate any sequence of integers that we would like.

The syntax of range is:

range(<start>, <stop>, <step>)

Note that <start>, <stop>, and <step> must all be of type integer.

The semantics is that the range of numbers will begin with <start>, be incremented by <step>, and go up to, but not include <stop>.

The <stop> is the only required portion of the command.

If <start> and <step> are not included, it will begin the sequence at 0 and increment by 1 each time.

For example, try these range commands:

range(5, 10) produces the sequence 5, 6, 7, 8, 9
range(2, 10, 2) produces the sequence 2, 4, 6, 8
range(5, 0, -1) produces the sequence 5, 4, 3, 2, 1
range(4) produces the sequence 0, 1, 2, 3

The range command creates a squence generator. If you want to see the sequence immediately, then your can typecast it into a list like this:

list(range(4)) will create the list [0, 1, 2, 3]

We can use range in for loops:

for i in range(1,5):
   print(i * i)

This loop will print the squares of the numbers from 1 to 4.