Counters and While Loops

Counters are integer variables used to keep track of how often a programming event occurs. For example, a counter may be used to keep track of how many times the user has tried to win a game.

A loop is a segment of program code that is repeated until a specific event occurs. Loops are often used in conjunction with counters, as the following code demonstrates:

# counter

i = 0

# while loop

while i < 5:

print (i)

i = i + 1 # optionally, i += 1

# let us know we're finished

print "Finished!"

In this example, the variable "i" is used to count the number of times the loop is executed. You will notice that "i" is used often as a loop variable, as well as "j" and sometimes "k" for nested loops (loops within loops).

The loop that is shown here is a "while" loop. While loops are used when we don't necessarily know how many times the loop will execute. We will also learn about "for" loops in a later lesson, which are used when we know exactly how many times a loop must execute.

Note that the lines below the while statement are indented. This tells Python which lines are to be run within the loop.

The statement "i = i + 1" is used to increment the loop counter. This value is tested after each iteration of the loop code to see if the condition (i < 5) is still true. As long as it's true, the loop will continue executing.

Assignment

Modify the example program so it prints all even numbers from 100 to 120 (inclusive).

Save as "023.py".

Additional Notes

In the above example, we used the "<" (less than) operator. Any of the following operators are legal:

< less than

> greater than

== equal to

!= not equal to

>= greater than or equal to

<= less than or equal to

Assignment

Modify 023.py so it prompts for a starting number and ending number.

Save as "023a.py".

Assignment

Modify 023.py by replacing the "while i < 5" statement with "while 1" (or "while True"). What happens to your program?

Do you understand why this is called an infinite loop?

(You do not have to save this program.)