Loops

We have used loops since the start of the course. Here we will learn how to build our own.

Loops allow us to repeat code a certain number of times or until a specific condition is met

For Loops

A for loop in Python iterated over or repeats a list of items - like the number 1-100. The following code iterates over 0,1,2,3 (remember that Python starts counting at 0)

import turtle
t=turtle.Pen()
t.speed(0)
for x in range(4):
    t.circle(100)
    t.left(90)

The code above makes a shape called a Rosette, made up from 4 circles.

A 4 circle Rosette

Some examples of ranges:

  • range(5) = 0, 1, 2, 3, 4

  • range(1) = 0

  • range(10) = 0, 1, 2, 3, 4, 5, 6, 7, 8, 9

  • range(2, 5) = 2 , 3 , 4

  • range(-2, 2) = -2, -1, 0, 1

To experiment with ranges, you can write out the numbers in the Idle Shell using the command list(range(4))

Letting the User Decide

It would be much better if we could ask the user how many circles they want to draw. We can ask the user for a number using Turtle with the code:

numberOfCircles = int(turtle.numinput("Number of circles",
                                        "How many circles in your rosette?", 6))

This stores the number in a variables called numberOfCircles.

Colourful Rosettes

While Loops

while loop repeats the sequence of actions many times until some condition evaluates to False. The condition is given before the loop body and is checked before each execution of the loop body. Typically, the while loop is used when it is impossible to determine the exact number of loop iterations in advance. This is very common in games where the loop is known as the GAME LOOP.

The syntax of the while loop in the simplest case looks like this:

while some condition:
    a block of statements

Python firstly checks the condition. If it is False, then the loop is terminated and control is passed to the next statement after the while loop body. If the condition is True, then the loop body is executed, and then the condition is checked again. This continues while the condition is True. Once the condition becomes False, the loop terminates and control is passed to the next statement after the loop.

For example, the following program fragment prints the squares of all integers from 1 to 10.

i = 1
while i <= 10:
    print(i ** 2)
    i += 1

We can also make the condition related to a string. Here we ask the user for a name and repeat it 100 times before asking them again. Only when the user enters an empty string do we exit the loop

# SayOurNames.py - lets everybody print their name on the screen

# Ask the user for their name
name = input("What is your name? ")

# Keep printing names until we want to quit
while name != "":

    # Print their name 100 times
    for x in range(100):
        # Print their name followed by a space, not a new line
        print(name, end = " ")
        
    print()   # After the for loop, skip down to the next line
    
    # Ask for another name, or quit
    name = input("Type another name, or just hit [ENTER] to quit: ")
print("Thanks for playing!")

Games are better with graphics though. Check out this simple game:

import turtle

t = turtle.Pen()

#draw a container
t.penup()
t.goto(200,200)
t.pendown()

t.right(90)
t.forward(100)
t.right(90)
t.forward(100)
t.right(90)
t.forward(100)

#return to the start
t.penup()
t.goto(0,0)
t.pendown()

#set up some variables
step = 50
direction = ''
counter = 0

while direction != 'q':
    direction = turtle.textinput("Directions", 'Which way?')
    if direction == 'f':
        t.forward(step)
    elif direction == 'l':
        t.left(90)
        t.forward(step)  

    #increase the counter by 1
    counter = counter + 1

#Writa a final message
style = ('Courier', 30, 'italic')
message = 'The End. You did it in ' + str(counter) + ' moves'
turtle.write(message, font=style, align='center')
turtle.hideturtle()

Challenge

Last updated

Was this helpful?