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:
for i in range(5):
print(i)
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:
for i in range(5):
print(i)
print(2*i)
print("====================================")
The block prints , and then a line, every time.
We don't have to use the variable i in the block at all:
for i in range(5):
print("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:
for i in range(5):
print("I'm telling you for the " + str(i) + "-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:
for i in range(5):
print("I'm telling you for the " + str(i+1) + "-th time, EngSci rocks")
(Fix the "1-th"/"2-th"/"3-th" issue yourself, if you'd like...)
Let's do something useful -- compute . 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 .
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