Module 5: Iteration (Loops)
What is Iteration?
Iteration is the process of repeating steps. In programming, we call these structures "loops". OCR ERL requires you to understand three types of loops: FOR, WHILE, and DO...UNTIL.
1. FOR loop (Count-Controlled)
Use a for loop when you know exactly how many times you want to iterate.
for i = 1 to 5
print("Loop number " + str(i))
next i
Exercise: Times Tables
Write an algorithm that asks the user for a number. Then, use a for loop from 1 to 10 to print out the times table for that number.
2. WHILE loop (Condition-Controlled)
Use a while loop when you don't know how many times to loop, but you want to continue as long as a condition remains true. The condition is checked at the start of the loop.
password = ""
while password != "secret"
password = input("Enter password:")
endwhile
print("Access granted!")
Exercise: Number Guesser
Create a variable `guess` set to 0. Use a `while` loop that continues as long as `guess` is NOT equal to 7. Inside the loop, ask the user to guess a number. After the loop ends, print "You guessed it!".
3. DO...UNTIL loop (Condition-Controlled)
Similar to the while loop, but the condition is checked at the end. This means the code inside the loop is guaranteed to run at least once.
do
numStr = input("Enter a positive number:")
number = int(numStr)
until number > 0
print("You entered: " + str(number))
Exercise: Validation
Use a `do...until` loop to continually ask the user to input "YES". The loop should end until the input is equal to "YES" (or "yes" if you use `.upper`). Let them know they succeeded afterwards.