Skip to content

Exercise 11 - Explore Loops

A loop is a set of instructions that repeat. The loop can go forever, never stopping. It can also go back over the code for a specific number of times. Or, it may run until an event occurs.

To make loops you will use the following code:

🐍 Python Script
while True: #Create a loop that repeats forever.

for shape in range(4): #Repeat the instructions a specific number of times, such as 4.
  • Open Thonny, create a new file, save it as loop.
  • Import the turtle library and set the screen size.

1. Make an Infinity Loop

A while loop runs over and over again. It stops only when a specific action occurs. If this never happens, then it will run forever. Try it!

loop

  • Draw a circle non-stop:
🐍 Python Script
#draw a circle 
while True:
    circle(60)

2. Count the Loops

  • A variable is a value that changes. Add a variable called loop.
🐍 Python Script
#draw a circle
loop = 0
while True:
    circle(60)
  • Count the number of loops:
🐍 Python Script
#draw a circle
loop = 0
while True:
    circle(60)
    loop = loop + 1
  • Write the number of loops:

numbered loop

🐍 Python Script
#draw a circle
loop = 0
while True:
    circle(60)
    loop = loop + 1
    write(loop)
  • To see the number of loops better, move each circle over a few steps:

moving loop

🐍 Python Script
#draw a circle
loop = 0
while True:
    circle(60)
    loop = loop + 1
    write(loop)
    forward(50)

3. Set the Number of Loops

You can set how many times a loop repeats itself.

  • Replace the while loop with a for loop:
🐍 Python Script
#draw a circle
loop = 0
for shape in range(4):
    circle(60)
    loop = loop + 1
    write(loop)
    forward(50)