for and while loops
You can think of a loop as continuously repeating the same instructions over and over until some condition is satisfied that breaks this loop. For example, the previous code was not a loop; since it was only executed once, we only checked a
once.
There are two types of loops in Python:
for
loopswhile
loops
for
loops have a specific number of iterations. You can think of an iteration as a single execution of the specific instructions included in the for
loop. The number of iterations tells the program how many times the instruction inside the loop should be performed.
So, how do you create a for loop? Simply, just like this:
for i in range(1, 20):
print(i)
We initialize this loop by writing for
to specify the type of loop. Then we create a variable i,
that will be associated with integer values from range (1,20)
. This means that when we enter this loop for the first time, i
will be equal to 1
, the second time it will...