Better Functions

Table of Contents

Grey overlay

Pink

Green

Blue

Cream

Liliac

Purple

Yellow

Fork me on GitHub

1 Lists

Learn It

  • A standard variable is handy for storing a single piece of information.
yourName='Jane'
yourAge=50
likeCrisps=True
  • 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')

print(someColours)

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="https://trinket.io/embed/python/b3e5f22215?runOption=console" 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)

colourList=['red','green','blue','orange','hotpink','purple']

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

tess.left(360/len(colourList))

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

w5.png

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