10 Loops

COMP 1701 Loops

Objectives

  • Understand the 2 main types of loops:

    • Condition-controlled

    • Count-controlled

  • Use Sentinel loops to conveniently process long lists of values.

  • Use loops to validate user input.

  • Understand nested loops (loops within loops).

Repetition Structures

  • Two broad categories:

    • Condition-controlled loops: Repeat an operation as long as some condition is True.

    • Count-controlled loops: Repeat an operation a specified number of times.

Condition-controlled Loops

  • Repeat statement(s) as long as some condition is True.

  • Plain-English Examples:

    • (Blackjack) Continue taking cards as long as hand totals less than 15.

    • Answer another question while there are more questions on the test and time.

    • Keep taking classes until they give you a degree.

Python’s While Loop

  • Use the while keyword to create a condition-controlled loop in Python.

  • Syntax: while condition: statement1 statement2 ...

  • The condition is tested before each repetition.

  • The condition can be any expression that evaluates to a boolean.

Example: Simple While Loop

  • This program keeps generating random numbers between 1-10 until a 5 is found.

from random import randint
five_was_found = False
while not five_was_found:
    rnd_number = randint(1, 10)
    print(rnd_number)
    five_was_found = rnd_number == 5
print('5 was found!')
  • Condition for loop: while not five_was_found checks if five is not found.

Differentiating Loops

  • A key difference:

    • repeat while checks for a positive condition to continue the loop.

    • repeat until checks for a positive condition to end the loop.

  • It requires inversion to rewrite for a while loop:

    1. Continue taking cards as long as hand totals less than 15.

    2. While there are more questions on the test and more time, answer another question.

    3. Keep taking classes until they give you a degree.

Infinite Loops

  • Occurs when the condition can’t be False.

  • Possible causes:

    • Logic errors in the condition.

    • Variables involved may not be modified properly inside the loop.

Count-controlled Loops

  • Repeat an operation a certain number of times.

  • Plain-English examples:

    • Peel and chop 5 bananas.

    • Roll the dice 3 times; take the highest number.

    • Add the exam dates for each of your courses to your calendar.

Creating a Count-controlled Loop with While

  • Example:

iteration_number = 0  # loop 5 times
while iteration_number < 5:
    iteration_number += 1
    print(f'iteration number: {iteration_number}')
print('done')
  • This uses a condition that checks the number of iterations.

Augmented Assignment Operators

  • Modify and reassign a variable in one step:

    • +=: x += 5 (equivalent to x = x + 5)

    • -=: y -= 2 (equivalent to y = y - 2)

    • *=: z *= 10 (equivalent to z = z * 10)

    • etc.

  • Useful for simplifying updates in loops.

While-loop Design Tips

  • Decide what to iterate (i.e. what operation is being repeated).

  • Decide on a loop control variable (LCV) as part of the loop’s condition.

  • Decide terminal condition(s): What value of the LCV will stop the loop?

  • Decide initial condition(s): Create LCV before the loop and set the initial value.

  • Update LCV inside the loop appropriately.

Python’s For Loop

  • Use for to iterate over a sequence.

  • Syntax: for variable in [value1, value2, ...]: statement1 statement2 ...

  • Each iteration assigns the next value in the list to the variable and runs the statements.

Simple For-loop Example

  • Print each number between 1 and 5:

for num in [1, 2, 3, 4, 5]:
    print(num)

The Range Function

  • A convenient way to generate numerical ranges:

    • range([start], stop, [step])

    • Examples:

      • range(5)[0, 1, 2, 3, 4]

      • range(2, 5)[2, 3, 4]

      • range(0, 5, 2)[0, 2, 4]

      • range(5, 0, -1)[5, 4, 3, 2, 1]

Example: For with Range

  • Inspect numbers and their squares:

for num in range(0, 10, 2):
    square = num ** 2
    print(f'the square of {num} is {square}')
string = 'hello world'
for index in range(len(string)):
    print(f'at index {index} is letter {string[index]}')

Sentinel Values

  • Loop through an unknown size series without repeatedly asking for termination.

  • A sentinel value signals the end of a sequence.

Input Validation Loops

  • Loops can help validate user input by prompting until valid data is entered.

  • Example: Ensure that password is at least 8 characters long.

Nested Loops

  • Loops can be nested within other loops.

  • Example: Planting beans in a field using pseudocode.

Break Statement

  • Use a break statement to exit a loop prematurely.

  • Example search for a letter in a string:

string = 'hello world'
for index in range(len(string)):
    if string[index] == 'o':
        print(index)
        break

C++ Comparison

  • Syntax and structure of loops vary by programming language:

while (condition) {
    // conditional code;
}
for (init; condition; increment) {
    // conditional code;
}
do {
    // conditional code;
} while (condition);