For Loops#

A for loop implements the repeated execution of code based on a loop counter or loop variable. for loops are used most often when the number of iterations is known before entering the loop. This is different from while loops which are conditionally based, and may run for an undetermined number of iterations.

In Python, for loops are constructed like so:

for [iterating variable] in [sequence]:
  [do something]

For example:

for x in 'hello':
    print(x)
h
e
l
l
o

In this example, the iterating variable was x and the sequence was the string hello. The for loop assigns each element in the sequence, in this case each character in the string, to the variable x and then executes the indented lines of code, one after another.

This works on iterable sequences stored to variables as well:

plaintext = 'mylittlesecret'

for char in plaintext.upper():
    print(char)
M
Y
L
I
T
T
L
E
S
E
C
R
E
T

Right now the only sequences we know are strings, but let’s learn another one, ranges.

Range#

One of Python’s built-in immutable (unchangeable) sequence types is range(). In loops, range() is used to control how many times the loop will be repeated. When working with range(), you can pass between 1 and 3 integer arguments to it:

range( [start], [stop], [step] )
  • start: the integer value that the sequence should begin at. If not included, the sequence will start at 0 by default.

  • stop: the integer that the sequence counts up to, but does not include. Must always be included in the call.

  • step: the integer the sequence should increase by (or decrease if you use a negative number) until the [stop] value is reached. If not include, the step will be 1 by default.

Let’s look at a simple range() call with one argument, range( [stop] ):

for i in range(4):
    print(i)
0
1
2
3

You can see that the iterating variable, i, is first set to the integer 0 since no [start] argument was used. The indented code then prints the current value of i. Next, i is set to the next value in the sequence, 1, which is printed. This process completes until 3 is printed. Since the [stop] value was set at 4, the sequence goes up to, but does not include 4, and the for loop now ends.

Now let’s look at a range( [start], [stop] ) example:

for integer in range(2, 7):
    print(2 * integer)
4
6
8
10
12

Here you can see that the iterating variable integer is first set to 2, and then twice this value is printed. This process continues until integer is set to 6 and then 12 is printed.

Another way to generate this same output is to use range( [start, [stop], [step] ):

for num in range(2, 14, 2):
    print(num)
2
4
6
8
10
12

This loop uses the [step] argument to assign values 2, 4, … , 10, 12, to the iterating variable num.

We’ll learn about more iterable sequences beyond strings and ranges later in the course. Examples include lists and arrays.