27. Condition controlled iteration

  • Remember, indenting your code indicates it is inside a loop
  • Always set your variable properly so the loop runs at least once
  • Don’t forget the colon to start the conditional statement
#Set x to 0
x = 0

#Loop while x is less than 5
while x < 5:
    print("looping")
    #Add 1 to x each time the loop runs
    x = x + 1

Tasks

  1. Type in the code and make sure that it works
  2. Change the code so it loops 20 times and prints out x each time
  3. Modify the program so it prints out the squares of the numbers 1-10 (hint: multiply the counter by itself)
  4. Save and label your code

Extension Task

Create a loop that will ask for a password and continue to do so until ‘apple’ is entered. A hint is shown below, but what other code do you need to make it work (use the example above to help)?

while password != "apple":