The while and for Statement

The while Statement

The while statement allows you to repeatedly execute a block of statements as long as a condition is true. A while statement is an example of what is called a looping statement. A while statement can have an optional else clause.

Example

number = 23
running = True

while running:
    guess = int(input('Enter an integer : '))

    if guess == number:
        print('Congratulations, you guessed it.')
        # this causes the while loop to stop
        running = False
    elif guess < number:
        print('No, it is a little higher than that.')
    else:
        print('No, it is a little lower than that.')
else:
    print('The while loop is over.')
    # Do anything else you want to do

print('Done')

Run this file

Output

$ python while.py
Enter an integer : 50
No, it is a little lower than that.
Enter an integer : 22
No, it is a little higher than that.
Enter an integer : 23
Congratulations, you guessed it.
The while loop is over.
Done

How It Works

In this program, we are still playing the guessing game, but the advantage is that the user is allowed to keep guessing until he guesses correctly - there is no need to repeatedly run the program for each guess, as we have done in the previous section. Because here we make use of the while statement.

We move the input and if statements to inside the while loop and set the variable running to True before the while loop. First, we check if the variable running is True and then proceed to execute the corresponding while-block. After this block is executed, the condition is again checked which in this case is the running variable. If it is true, we execute the while-block again, else we continue to execute the optional else-block and then continue to the next statement.

The else block is executed when the while loop condition becomes False - this may even be the first time that the condition is checked. If there is an else clause for a while loop, it is always executed unless you break out of the loop with a break statement.

The for loop

The for…in statement is another looping statement which iterates over a sequence of objects i.e. go through each item in a sequence. We will see more about sequences in detail in later lessons. What you need to know right now is that a sequence is just an ordered collection of items.

Example (save as for.py):

for i in range(1, 5):
    print(i)
else:
    print('The for loop is over')

Output

$ python for.py
1
2
3
4
The for loop is over

How It Works

In this program, we are printing a sequence of numbers. We generate this sequence of numbers using the built-in range function.

What we do here is supply it two numbers and range returns a sequence of numbers starting from the first number and up to the second number. For example, range(1,5) gives the sequence [1, 2, 3, 4]. By default, range takes a step count of 1. If we supply a third number to range, then that becomes the step count. For example, range(1,5,2) gives [1,3].

NOTE: Remember that the range extends up to the second number i.e. it does not include the second number.

Note that range() generates only one number at a time, if you want the full list of numbers, call list() on the range(), for example, list(range(5)) will result in [0, 1, 2, 3, 4]. Lists are explained in the data structures lessons.

The for loop then iterates over this range - for i in range(1,5) is equivalent to for i in [1, 2, 3, 4] which is like assigning each number (or object) in the sequence to i, one at a time, and then executing the block of statements for each value of i. In this case, we just *print the value in the block of statements.

Remember that the else part is optional. When included, it is always executed once after the for loop is over unless a break statement is encountered.

Remember that the for…in loop works for any sequence. Here, we have a list of numbers generated by the built-in range function, but in general we can use any kind of sequence of any kind of objects! We will explore this idea in detail in later chapters.