At My Fingertips
Rapid Playground
In this activity you learn to compose multiple graphics and you practice creating functions.
Did you mention five concentric circles? With increasing diameters? Alternating between black and white colors?
circle
You probably already know the drill:
We need circles, so let's import the circle
function from your toolbox.
(If you don't have circle
in your toolbox,
do the Simple Snowman activity now.)
target
Implement the target
function using the circle
function you imported.
The target is composed of 5 circles,
one on top of the other,
alternately black and white.
The innermost circle is black.
Use the pytamaro overlay function as well as the imported black
and white
colors.
If you found your code looked repetitive, check out this implementation here!
def target(diameter: float) -> Graphic:
c0 = empty_graphic()
c1 = overlay(c0, circle(diameter / 5 * 1, black))
c2 = overlay(c1, circle(diameter / 5 * 2, white))
c3 = overlay(c2, circle(diameter / 5 * 3, black))
c4 = overlay(c3, circle(diameter / 5 * 4, white))
c5 = overlay(c4, circle(diameter / 5 * 5, black))
return c5
You see five lines that are almost identical. We will later learn how to use ways to write just one of those lines, and to have it do all five circles! Python offers several ways to achieve this: loops, recursion, higher-order functions, and comprehensions. To use any of these four ways, we will need to look out for similarities and differences in our code (or in the graphics).
The structure of the code kind of mirrors the structure of the graphic we try to compose. If the graphic has a repetitive structure, our code should have a repetitive structure as well. If the repeated pieces of code are very similar, then we will be able to just write them once, and to use programming language features to have them repeated as many times as we need.
For now, we just had to write five calls to circle
, and at least four calls to overlay
.
That's a bit of repetitive work, but just wait until you have to do that 100 or a million times!
This activity has been created by LuCE Research Lab and is licensed under CC BY-SA 4.0.
Target
PyTamaro is a project created by the Lugano Computing Education Research Lab at the Software Institute of USI
Privacy Policy ⢠Platform Version 1cd5229 (Tue, 05 Nov 2024 16:55:57 GMT)