Chapter 6 Loop Statement

6.3 Branching Nested in a Loop¶

As other statements, an if statement can be put into the loop body of a while statement. For a simple example, suppose that a user needs to print all the integers from 1 to 100 that are not multiples of 3. One solution is to set up a loop variable i that counts from 1 too 100, in the same way as the earlier example that counts from 0 to 2, while printing out the value of i only when it is not a multiple of 3.

In the example above, the print statement is put under the Boolean condition that i%3 != 0. Hence in a dynamic execution sequence, it will be executed only when i is not a multiple of 3. The analysis of if statements nested in while loops is similar to the analysis of nested if statements—the execution of each statement can be analyzed separately, in an outer-intra hierarchy. Note that the underlying mechanism of each individual if and while statement, no matter whether nested or not, is the same and relies on the relevant Boolean expression only. Again, a useful technique for analyzing a combination of looping and branching statements is to write a control flow diagram.

For a more complex example, in which the Boolean condition of the loop is affected by the execution of an if statement in the loop body, take the following number guessing game. Suppose that the computer generates a random number between 1 and 100, and the user tries to guess it. Every time the user enters a guess, the computer tells whether the guessed number is greater than, equal to, or smaller than the answer. In case the guess is correct, the game ends with the user winning the game. Otherwise the user is allowed to enter another guess. The game repeats until the user finds the answer. An example implementation of the game is as follows:

# [guess.py]
import random
answer = random.randint(1, 100)
wins = False # looping condition
while not wins:
    guess = int(input('Your guess is: '))
    if guess == answer:
        print ('You win!')
        wins = True
    elif guess > answer:
        print ('Too large ')
    else:
        print ('Too small ')

guess.py uses the Boolean variable wins to record whether the user has won the game. The variable is initialized to False. Until wins is changed to True, the program repeats asking the user for a guess, and giving relevant feedback to the user. wins is set to True if the answer at the current iteration is correct. An example execution of guess.py is shown below.

> python guess.py
Your guess is: 50
Too large
Your guess is: 25
Too small
Your guess is: 37
Too small
Your guess is: 43
Too large
Your guess is: 40
Too small
Your guess is: 42
Too large
Your guess is: 41
You win!

The program above can be made more challenging by setting a limit on the number of guesses allowed.

# [guess_limit.py]
import random
limit =7
answer = random.randint(1, 100)
guesses=0
wins = False
while guesses < limit and not wins:
    guess = int(input('Your guess is: '))
    guesses += 1
    if guess == answer:
        print ('You win!')
        wins = True
    else:
    if guess > answer:
        print ('Too large ')
    else:
        print ('Too small ')
if not wins:
    print ('You lose.')

guess_limit.py uses an additional variable, guesses, to count the number of guesses that the user has already made. An extra condition that guesses is smaller than limit is added to the Boolean expression for while, which decides whether to allow the user to guess again. In addition, when the loop finishes, either wins is True or guesses is equal to limit. In the latter case, the user has lost the game. A corresponding else statement block is added so that a message is shown to the user the the game finishes without being won.

Loops can also be put in other loops, resulting in nested loops.

© Copyright 2024 GS Ng.

Next Section - 6.4 Break and Continue