### For loops¶

Here is the syntax for for-loops:

for <i> in range(<N>):
<block>



This statement repeats <block> N times, while setting the variable <i> to 0, 1, 2, ..., N-1. Here is a long way to write this out:

Set i to 0, execute block Set i to 1, execute block Set i to 2, execute block .... Set i to N-1, execute block

Here is a very simple example:

In [1]:
for i in range(5):
print(i)

0
1
2
3
4


The block here simply prints i. So we print everyting from 0 and up to 5-1=4. Here is a slightly more complicated block:

In [2]:
for i in range(5):
print(i)
print(2*i)
print("====================================")

0
0
====================================
1
2
====================================
2
4
====================================
3
6
====================================
4
8
====================================


The block prints $i$$i$, $2i$$2i$ and then a line, every time.

We don't have to use the variable i in the block at all:

In [4]:
for i in range(5):
print("EngSci rocks")

EngSci rocks
EngSci rocks
EngSci rocks
EngSci rocks
EngSci rocks


If we don't use i inside the block, we simply repeat the block 5 times. We can also mix up uses of i together with things that don't change:

In [5]:
for i in range(5):
print("I'm telling you for the " + str(i) + "-th time, EngSci rocks")

I'm telling you for the 0-th time, EngSci rocks
I'm telling you for the 1-th time, EngSci rocks
I'm telling you for the 2-th time, EngSci rocks
I'm telling you for the 3-th time, EngSci rocks
I'm telling you for the 4-th time, EngSci rocks


That is a little strange -- suppose we don't want to have a "0-th" time there. One possibility is to use i+1 instead of i there:

In [6]:
for i in range(5):
print("I'm telling you for the " + str(i+1) + "-th time, EngSci rocks")

I'm telling you for the 1-th time, EngSci rocks
I'm telling you for the 2-th time, EngSci rocks
I'm telling you for the 3-th time, EngSci rocks
I'm telling you for the 4-th time, EngSci rocks
I'm telling you for the 5-th time, EngSci rocks


(Fix the "1-th"/"2-th"/"3-th" issue yourself, if you'd like...)

### Computing a to the power of n¶

Let's do something useful -- compute ${a}^{n}$$a^n$. How to do that with a for-loop? We need to frame the problem as one of repeating some kind of action. Here's an action we can repeat: first, set the variable res (for "result") to 1, and then repeatedly apply the action res = res * a, n times. The end result will be ${a}^{n}$$a^n$.

In [7]:
def my_pow(a, b):
'''Return a to the power of b

Arguments:
a -- a non-zero integer
b -- a non-negative integer'''

#Idea: repeat res = res * a
#n times
#Note: if b is 0, things still work out, since we repeat res *= 1
#0 times, so that res is still 1 after the loop terminates,
#which is what we return, and a^0 is in fact 1.
res = 1
for i in range(b):
res = res * a

return res