LogoLogo
Terminal
  • Attic Lab
  • Getting Started
  • Crest Gold
  • Crest Silver
  • Videos on Computation
  • PI PICO (CIRCUITPYTHON)
    • Getting Started
    • Pin Out Diagram
    • Breadboards
    • 1. Led Blink
    • 2. RGB
    • 3. OLED
    • 4. Sensors
    • 5. Wifi
    • 6. Servos
  • Arduino
    • Getting Started
    • Pin Out Diagrams
      • Mega2560 R3
    • Programming
      • Arduino C - Cheat Sheet
    • Buttons
      • Momentary Switches
    • Display
      • LEDs
      • 7 Segment Displays
      • LCD Displays (GPIO)
      • LCD Displays (SPI)
      • OLEDs
    • Communication
      • Antenna Theory
      • Lora
      • Wifi
        • Boards
    • Project Ideas
    • Motion
      • DC Motors
      • Servo Motors
      • Stepper Motors
  • Microsoft Office
    • Word
    • Powerpoint
    • Excel
  • The Terminal
    • Basics
    • Cheat Sheet
    • Games
      • Level 1 - Bashcrawl
      • Level 2 - Bandit
  • TinkerCad
    • Gallery
    • Getting Started
    • Basic Operations
    • Basic Skills
    • Projects
      • Locking Container
  • Python
    • Hello World
    • Turtle Graphics
      • Strings in Turtle Graphics
      • Cheat Sheet
    • Variables
    • Loops
    • If Statements
    • Functions
    • Games
      • Pong
  • Raspberry Pi
    • Setup
      • Changing The Hostname
      • Headless Setup
      • Kiosk Mode
    • Remote Connections
    • Displays
      • Memory
        • External HD
      • HyperPixel 4.0
  • Ultimaker 3D Printing
    • The Thingiverse
    • Preparing the File
    • Printing
    • Calibration Prints
    • Print Set
  • Fusion 360
    • Getting Started
    • Design Tutorials
      • Tweezers
      • Mars Rover Wheel
    • Surface Modeling
  • Electronics
    • References
    • Antenna Theory
    • LoRa
  • PCB Milling
    • FlatCam
    • Candle
    • PCB Milling
  • Projects
  • Projects
    • Star Map Necklace
    • Ideas Respository
  • Latex
    • What is LaTeX?
    • Getting Started
    • Structure
    • Page Size & Margins
    • Styling
    • Images
    • Lists
    • Tables
    • Mathematics
      • Superscript and Subscripts
      • List of Symbols
      • Fractions and Binomials
      • Integrals, Sums & Limits
    • Colors
  • Web Development
    • The Internet
    • Intro to HTML
    • Basic Elements
    • Basic Styling
Powered by GitBook
On this page
  • For Loops
  • Letting the User Decide
  • Colourful Rosettes
  • While Loops
  • Challenge

Was this helpful?

  1. Python

Loops

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

PreviousVariablesNextIf Statements

Last updated 5 years ago

Was this helpful?

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.

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))

Modify the for loop in the code above to draw a Rosette made from 10 circles. It should like look the picture below.

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.

Modify your code so that the it asks the users how many circles they want and then draw them to the screen.

Colourful Rosettes

Using the Turtle commands that you have already learnt, experiment to make more interesting patterns. For example, try adding a second smaller circle straight after the first.

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

Ask the user for a number and use a while loop to output the sum of integers 1,2,3.. etc up to that number. Remember that to do maths with an input we have to inclose the input function in eval() to tell Python that it is a number. eg.

number = eval(input('Which number'))

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()

Improve the code by including command to go right and backwards

Modify the code to create a better game. Eg. create a race track before the book starts so that the user has to go around the track in the smallest number of moves

Challenge

As a future athlete you just started your practice for an upcoming event. Given that on the first day you run x miles, and by the event you must be able to run y miles.

Calculate the number of days required for you to finally reach the required distance for the event, if you increases your distance each day by 10% from the previous day.

Print one integer representing the number of days to reach the required distance.

A 4 circle Rosette