Question

colours =  [turtle.color("red"),turtle.color("blue"),turtle.color("yellow"),turtle.color("green")]

fred = colours[0],turtle.forward(100),turtle.left(90),colours[1],turtle.forward(100),turtle.left(90),colours[2],turtle.forward(100),turtle.left(90),colours[3],turtle.forward(100),turtle.left(90)

Attemping to make a square with 4 different colours from a list, type(colours[0]) returns class Nonetype. How can I access the colours from my list?

Était-ce utile?

La solution

Your code:

colours = [turtle.color("red")]

Will run the function turtle.color("red"), and store the return value in the list.

This is exactly the same as doing:

colours = [None]

If you call colours[0] you get the return value, not the function. Python has no idea if the None ended up there through a function call, or if you just assigned it manually.

You only posted 2 lines of code, so I don't quite know what the context is here, but you may want to do something like:

colours =  [lambda: turtle.color("red"), lambda: turtle.color("blue")]

What this does, is store a lamba (or 'anonymous function') in your list. This function is not executed. You will now get:

>>> colours[0]
<function <lambda> at 0x80089e710>

And you can execute this as many times as you want by appending parenthesis, like so: colours[0]()

This technique is known as 'currying' by the way.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top