Better Functions

Table of Contents

Grey overlay








Fork me on GitHub

1 Lists

Learn It

  • A standard variable is handy for storing a single piece of information.
  • Sometimes, it's handy to store several pieces of information so that we can access them all when we need them. For this, we use a list.
  • Type these commands in the INTERPRETER one at a time to get the hang of manipulating lists:

#+BEGINEXAMPLE someColours=['Red','Blue','Pink','Black']

print(someColours[0]) someColours.append('Green')


someColours.sort() print(someColours)

someColours.reverse() print(someColours)

someColours.pop() print(someColours)

someColours.pop(1) print(someColours) #+endsrc

  • You can type the commands into this Trinket, if you find it easier…

<iframe src="" width="100%" height="600" frameborder="0" marginwidth="0" marginheight="0" allowfullscreen=""></iframe>

Code It

  • Using lists, we can get more flexibility over the patterns we can create.

#+beginsrc python import turtle

wn = turtle.Screen() wn.bgcolor("white") wn.title("List Practice")

tess = turtle.Turtle() tess.pensize(5)

def colouredSquare(sideLength,newColour): tess.color(newColour) for x in range(4): tess.forward(sideLength) tess.left(90)


for eachColour in colourList: colouredSquare(75,eachColour) # Draw a square in the current colour.


wn.mainloop() #+ENDEXAMPLE

  • As always, this Trinket may be handy to use to experiment with…

2 Assessment

Badge It

  • Silver: Modify the code to draw the first square with side lengths of 20, the second with size 40, third with 60 and so on.
  • Gold: Change the code so that the user can enter five colours that are used to draw a pattern of your choice.
  • Platinum: Change the code so that the user can enter as many colours as they like, and have a shape drawn with that many sides. E.g.
Name a Python colour (XYZ when done): red
Name a Python colour (XYZ when done): blue
Name a Python colour (XYZ when done): green
Name a Python colour (XYZ when done): XYZ
Here goes...


  • Tip: You'll need to use a WHILE loop to make this work.