Objective 7: Understand
condition
controlled iterations
Objective 7: Understand condition controlled iterations
Iterations & loops
Keyword: while
while is used to repeat a section of code a variable number of times.
while indicates the condition to stop repeating
The indented code underneath is the code to repeat.
Syntax:
choice = int(input("Please select an option in the range 1-3: "))
while ((choice <=1) or (choice >=3)):
choice = int(input("Please select an option in the range 1-3: "))
2
Objective 7: Understand condition controlled iterations
Iterations & loops
We can also use a while loo[ to count the number of times a section of code has run.
import random
ballsOut = 1
while (ballsOut < 8):
print([Link](1,50))
ballsOut = ballsOut +1
What does this code do?
3
Objective 7: Understand condition controlled iterations
Iterations & loops
Analysing the program:
import random
ballsOut = 1 Initialise the counting variable
Start loop while (ballsOut < 8): End loop condition
print([Link](1,50))
Increment ballsOut = ballsOut +1
4
Objective 7: Understand condition controlled iterations
Iterations & loops
Side by side analysis:
import random import random
ballsOut = 1 for counter in range (1, 7):
ball = [Link](1,50)
while (ballsOut < 8): print(ball)
print([Link](1,50))
ballsOut = ballsOut +1
5
Objective 7: Understand condition controlled iterations
Try the Objective 7: Problems
Menu selection problem
Compound interest problem
Guess the number game problem
Gamertag problem
Rock, paper, scissors problem
Happy numbers problem
XP problem