Repeated Steps
Loops (repeated steps) have iteration variables that change each time through a loop. Often these iteration variables on through a sequence of numbers.
n = 5
while n > 0:
print(n)
n = n - 1
print('Blastoff!')
print(n)
/*Output
5
4
3
2
1
Blastoff!
0
*/
Breaking Out of a Loop
- The break statement ends the current loop and jumps to the statement immediately following the loop
- It is like a loop test that can happen anywhere in the body of the loop
while True:
line = input('> ')
if line == 'done':
break;
print(line)
print('Done!')
> hello there
hello there
> finished
finished
> done
Done!
Finishing an Iteration with continue
The continue statement ends the current iteration and jumps to the top of the loop and starts the next iteration
while True:
line = raw_input('> ')
if line[0] == '#':
continue
if line == 'done':
break
print(line)
print('Done!')
Indefinite Loops
- While loops are called “indefinite loops” because they keep going until a logical condition becomes False
- The loops we have seen so far are pretty easy to examine to see if they will terminate or if they will be “infinite loops”
- Sometimes it is a little harder to be sure if a loop will terminate
Definite Loops
- Quite often we have a list of items of the lines in a file - effectively a finite set of things
- We can write a loop to run the loop once for each of the items in a set using the Python for construct
- These loops are called “definite loops” because they execute an exact number of times
- We say that “definite loops iterate through the members of a set”
A Simple Definite Loop
for i in [5, 4, 3, 2, 1]:
print(i)
print('Blastoff!')
/*Output
5
4
3
2
1
Blastoff!
*/
A Simple Definite Loop
Definite loops (for loops) have explicit iteration variables that change each time through a loop. These iteration variables move through the sequence or set.
Looking at In…
- The iteration variable “iterates” through the sequence (ordered set)
- The block (body) of code is executed once for each value in the sequence
- The iteration variable moves through all of the values in the sequence
Loop Idioms: What We Do in Loops
Note: Even though these examples are simple, the patterns apply to all kinds of loops