View Single Post
Old 2019-12-25, 00:52   #14
Dylan14
 
Dylan14's Avatar
 
"Dylan"
Mar 2017

2·293 Posts
Default For loops part 1: Introduction to for loops

So far, we covered one part of the backbone of programs: the if/else/elif statements. Now we move to loops. A loop (in coding lingo) is a sequence of statements which is specified once, but can be run many times, even an infinite number of times. There are several types of loops:
* for loops (run a piece of code x number of times, and we keep track of how many times we run the code with a counter)
* while loops (while some boolean statement is true, run a piece of code and break out when the statement is no longer true)
* for each loops (run a piece of code on every single item in a collection of objects)
* do...while loops (run a block of code at least once, and then repeat the block depending on the truth value of a statement at the end of the block)
For the next couple of sections, we will deal with the for loop.

For loop syntax:
The for loop in Python has the following syntax:
Code:
for <variable> in <iterable object>:
      do something
Here, <variable> is known as the iterator. The iterable object can be a list, a string, a tuple, or any object which can be iterated over(*). After this, we follow with a colon and then an indented block starts. Inside the indented block is code that should be iterated over, through all the objects in the iterable object.
Some notes here:
1. The object that we are iterating over must be iterable. You can't iterate over an integer, otherwise you will get a error.
2. The indented block must have something, it can't be empty. Like with the if/else construct, you can use the pass function if you don't want to run anything inside the loop.
3. You can have nested for loops. In this case the inner-most loop will iterate through, then (if you've coded things correctly) the next inner loop will iterate and the innermost one will reset, and so on.
A simple example:

Let us print out the exponents that are known to produce Mersenne Primes (which is used in several programs, like dmdsieve). We can do this using a for loop:
Code:
exp_list = ['2', '3', '5', '7', '13', '17', '19', '31', '61', '89', '107', '127', '521', '607', '1279', '2203', '2281', '3217', '4253', '4423', '9689', '9941', '11213', '19937', '21701', '23209', '44497', '86243', '110503', '132049', '216091', '756839', '859433', '1257787', '1398269', '2976221', '3021377', '6972593', '13466917', '20996011', '24036583', '25964951', '30402457', '32582657', '37156667', '42643801', '43112609', '57885161', '74207281', '77232917', '82589933']
for exp in exp_list:
     print(exp)
Here, we are iterating over a list called exp_list, and our variable is called exp (**). For each item in the list, we print it.
This is an example of a for each loop, even though in Python we are simply using for and in.

The range function:

Say we want to run a loop a certain number of times. To do this, we can use the range function. The syntax of the function is as follows:

Code:
range(start, stop, step)
The function requires one argument, stop, and start and step are optional. The arguments do the following things:
start - specifies the start of the sequence. By default, this is 0.
stop - a required argument, which specifies the upper bound of the sequence. This number is not included in the range.
step - specifies the difference between each result. By default, this is 1.
A few notes:
Start, stop and step must be integers.
The arguments can be negative or positive.
Step has to be non-zero, otherwise you will get a ValueError.
A simple example with range:
Code:
x = range(6)
for i in x:
     print(i)
which yields:
Code:
0
1
2
3
4
5
so you can see that 6 is not included.

Slightly more complicated example with range, with start and step
Code:
y = range(-1,12,3)
for i in y:
     print(i)
which yields:
Code:
-1
2
5
8
11
The next increment, which would be 14, is greater than 12 and therefore is not printed.
There are similar functions included in numpy called arange and linspace which deal with arrays. We will deal with these later when we mention numpy.

Factorial, revisited:
Recall that when we covered functions we defined the factorial function, using if, else and elif. We can do a similar thing with for loops, with a few if's to cover some of the unit cases (***):
Code:
def factorial(n):
    fac = 1
    if n < 0:
        raise ValueError("Factorial is defined for positive integers.")
    if n == 0:
        return fac
    for i in range(n,0,-1):
        fac = fac*i
    return fac
Note here we use all the arguments of the range function. As a test, try the following inputs:
0 - should get 1
1 - should get 1
3 - should get 6
.2 - should get a TypeError

(*) Most things in Python can be made iterable (even functions!). We will deal with this (as well as the iter function) later.
(**) Actually, it doesn't matter what I call the iterator. I just need to note that whatever I call it, I must use that throughout that code block.
(***) An important thing to do when testing code is to run it on some unit cases. For example, for the factorial function, we should test it on 0, since 0! is defined to be one.

Last fiddled with by Dylan14 on 2019-12-25 at 00:57 Reason: factorials were first mentioned in functions
Dylan14 is offline