Loops

Loops are used to run code over and over again. There are two types of loops:
  • for loops - run a predetermined number of times
  • while loops - run as long as a specified condition is true
Example of a for loop that runs 5 times:
for i in range(5):
  print(i)
# prints 0, 1, 2, 3, 4
Make sure to indent each line in the body of the loop. The variable i starts at 0, and increases by 1 on each iteration of the loop. The loop variable is often called i, but it can be called anything. The range function determines the number of times the loop runs. If one argument is passed, the loop variable goes from 0 to one less than the argument value. If two arguments are passed, the loop variable goes from the first argument value to one less than the second argument value.
Example of a while loop that runs as long as the command is not "quit":
count = 0
command = ""
while command != "quit":
  command = input("Enter a command: ")
  count = count + 1
  print(f"Loop has repeated {count} times.")
The loop runs as long as the condition command != "quit" is true. Once the user types "quit", the loop stops. To have a loop run forever, simply put True for the condition.

Exercise 1 of 5

Write the start of the loop to print the numbers 0 through 9.
# start of loop here
  print(number)

Your code

Exercise 2 of 5

Write the start of the loop to print the even numbers from 20 to 30.
# start of loop here
  print(i * 2)

Your code

Exercise 3 of 5

Write the start of the loop to print random numbers until it prints 5.
import random
number = 0
# start of loop here
  number = random.randint(0, 9)
  print(number)

Your code

Exercise 4 of 5

Write the start of the loop to run until the user enters the command "quit".
command = ""
# start of loop here
  command = input("Enter a command: ")

Your code

Exercise 5 of 5

Write the start of the loop to run forever.
# start of loop here
  print("Still going...")

Your code