At My Fingertips
Artists sometimes collect a list of colors in a "palette".
Here is a palette of colors we name artsy_rainbow
.
Each color is created from its red, green, and blue components using the rgb_color function.
Let's program a function that takes a palette (a list of colors) and returns a graphic visualizing that palette. The graphic consists of one circle per color, and all circles are placed beside each other. The first color's circle is placed on the left.
A call to horizontal_palette(artsy_rainbow)
should look like this:
Now let's create a circle composed of sectors, one sector for each color.
We use the enumerate
function provided by Python. We call the function with a list of colors, and it produces a list of index-color tuples.
The for-loop thus iterates over the list of tuples, and each time gives us one such tuple. We destructure that tuple into the variables index
and color
.
Thus, in the loop body we have available the current index
(0 to 23 in our case),
the current color
, the angle of a single sector (360 / 24 = 15), and result
, the variable accumulating the resulting graphic.
We would like to have a black outline around each sector, like this:
The outline consists of two parts: a rounded arc, and straight lines. To get the rounded arc, we place a slightly smaller colored sector on top of a black sector. To get the straight lines, we place a black rectangle on top of the sector.
Finally, let's compose multiple outlined color circles into a color swirl.
To do this, we rotate each color circle a bit more (or less) than the prior circle.
Let's name this "between-circle rotation" the twist
:
A twist
of 0.0 means the absence of twist, a twist
of -1.0 means each circle is rotated clock-wise by one segment with respect to the next smaller circle,
and a twist
of 1.0 means each circle is rotated counter-clock-wise by one segment with respect to the next smaller circle
We hope you like these color swirls!
Save your color_swirl
function in your toolbox.
You might want to use it somewhere else in the future!
You learned how to:
len(l)
for e in l
for (e, i) in enumerate(l)
for i in range(len(l))
for i in range(n)
Note that all four ways to iterate are based on the exact same for
-construct.
The difference is that in each of the four cases we provide a different list to iterate over:
l
enumerate(l)
range(len(l))
range(n)
The second-to-last case is just a variant of the last case,
because len(l)
evaluates to a number,
and thus we call range
with a number as an argument in both cases.
This activity has been created by LuCE Research Lab and is licensed under CC BY-SA 4.0.
Color Swirl
PyTamaro is a project created by the Lugano Computing Education Research Lab at the Software Institute of USI
Privacy Policy • Platform Version c3a8286 (Mon, 14 Oct 2024 13:30:28 GMT)