Layer Cake using Python Turtle

layer-cakeIn this challenge we will use Python Turtle to create and draw a layer cake.

The code provided at the bottom of this blog post is using a few computing concepts such as:

  • A list to store the parameters of the layers of our cake,
  • A dictionary to match specific colour codes to different ingredients,
  • (x,y) coordinates to position the turtle on the screen.


List?


In Python, a list is used to save a collection of values. For instance, to save all the different days of the week we could declare a variable called “daysOfTheWeek” and assign a list as follows (Notice the use of square brackets):

Based on this what do you think len(daysOfTheWeek) would return?
What’s about daysOfTheWeek[0]?
Or daysOfTheWeek[3]?

Looping through a list


It is possible to access each value of a list one at a time using a for loop. Look at the following code to print the seven days of the week.

Dictionary?


By completing this challenge we are going to learn about Python dictionaries.
In Python, a dictionary consists of pairs (called items) of keys and their corresponding values.

Python dictionaries are also known as associative arrays or hash tables. The general syntax of a dictionary is as follows:
PythonDictionary

Layer Cake Challenge


In this challenge we decided to create a list called layers to store the parameters (height and ingredient) of each layer.

Check the code below and add more layers from line 42. You can use any of the ingredients from the dictionary called ingredients.

layer-cakes

Share Button
Posted in Computer Science, Python - Beginner, Python Challenges Tagged with: , ,

Our Latest Book

Follow this blog