Skip to main content

Featured

Space Explorers Book 7: Answers and Explanations

Memunic Space Explorers › Book 7: Memoon and the Search for Another Home › Answers and Explanations Answers and Explanations Habitable means life could live there; inhabited means life does live there. A world can be habitable and empty, as an unoccupied flat has a roof and water but nobody in it. The Moon has almost no air, so water would boil or freeze, and its gravity is only about one-sixth of Earth’s, too weak to keep air. Accept also: no greenhouse blanket, so it swings between very hot and very cold. Venus. It matches Earth in size and roughly in mass, but its thick carbon dioxide air traps heat, making it hot and crushing. “Twin” is only true for size and weight. A dip of 1 per cent means (planet width divided by star width) squared is 0.01, so the ratio is 0.1: the planet is about a tenth as wide as the star. Repeats at the same gap show the planet is going round the star in 12 days, and rule out a one-time event such as a passing object. A planet shines only by reflected l...

Byte by Byte Book 6: Chapter 9 – Drawing with Python Turtle

Byte by Byte › Book 6: Python, Data and How Computers Work › Chapter 9: Drawing with Python Turtle

Chapter 9: Drawing with Python Turtle

You will learn: how to use Python's turtle module to draw, how to move and turn the turtle, how to use loops to draw regular polygons using exterior angles, how to use the pen, colours, fills and coordinates, and how to combine loops and maths to create patterns such as stars, spirals and rangoli designs.

🌟 The Adventure

The Glow Wall rose above Pearlhaven like a giant black cliff. Long ago, the Old Makers had covered it with a special shimmering coral. When the Engine sent light along it, glowing lines appeared, like drawing with a torch on a dark night.

"The Engine once drew on it with something called the Light Turtle," said Octavia. "A tiny point of light that moved where it was told, leaving a glowing trail behind it."

Kachui's spectacles nearly fell off his nose. "A turtle that draws?"

"A turtle that draws, carrying a pen in its tail," said Octavia. "It goes forward, it turns, it lifts the pen, it puts it down. But it only understands Python, and I never learned how to make it draw anything more than a wobbly line."

The Festival of Tides was nine days away. Thousands of fish would gather in the square. They had not seen a single picture on the Glow Wall for thirty years. Memoon looked up at the vast dark surface and felt very small.

Then she remembered her first ever program in Scratch, years ago, when she had made a sprite walk in a square. "Forward, turn, forward, turn," she said slowly. "Kachui. I think I've done this before."

💡 Learn With Memoon

The turtle module. Python comes with a module called turtle . It opens a drawing window with a small arrow or turtle shape in the middle. You give the turtle commands, and as it moves, it draws a line with its pen. It is one of the oldest ideas in teaching programming: an educational robot turtle drew on paper in the 1960s and 1970s, in a language called Logo, and Python's turtle copies it.

Your first drawing.

import turtle
t = turtle.Turtle()    # make a turtle called t
t.shape("turtle")      # make it look like a turtle
t.forward(100)         # move forward 100 steps, drawing a line
t.left(90)             # turn left 90 degrees
t.forward(100)
turtle.done()          # keep the window open

Save this as first_drawing.py and press F5. A window opens and the turtle draws two sides of a square.

Important: never save your own file as turtle.py . If you do, Python will import your file instead of the real turtle module, and nothing will work.

Turtle commands.

CommandWhat it does
t.forward(100)Move forward 100 steps (pixels)
t.backward(50)Move backward 50 steps
t.left(90)Turn left (anticlockwise) by 90 degrees
t.right(45)Turn right (clockwise) by 45 degrees
t.penup()Lift the pen: move without drawing
t.pendown()Put the pen down: draw again
t.goto(x, y)Move straight to the point (x, y)
t.setheading(90)Point in a direction: 0 is right (east), 90 up, 180 left, 270 down
t.circle(50)Draw a circle with radius 50
t.color("red")Set the pen colour
t.pensize(5)Set the line thickness
t.fillcolor("yellow")Set the colour used for filling shapes

t.begin_fill() and Fill in the shape drawn between them

t.end_fill()
t.speed(0)Set the speed: 1 is slow, 10 is fast, 0 is fastest
t.hideturtle()Hide the turtle shape

The t. before each command means "tell the turtle called t to do this", just like random. meant "use the random module". You can make several turtles with different names and control each one separately.

The screen. The drawing window is the screen. You can control it too:

screen = turtle.Screen()
screen.bgcolor("black")       # background colour
screen.title("Glow Wall")     # window title

Coordinates. The turtle window uses x and y coordinates exactly like the Scratch stage: (0,

  1. is the centre, x increases to the right and y increases upwards. Negative x is left of centre;

negative y is below it. The turtle starts at (0, 0) facing right.

Loops make shapes. Drawing a square by repeating forward, left four times is the perfect job for a for loop:

for side in range(4):
    t.forward(100)
    t.left(90)

The polygon rule. Why 90 degrees? When the turtle walks all the way round any closed shape and ends up facing the way it started, it has turned through exactly 360 degrees in total. A square has 4 corners, so each turn is 360 ÷ 4 = 90 degrees. That turn is the shape's exterior angle. For any regular polygon (all sides and angles equal) with n sides:

exterior angle = 360 ÷ n
ShapeSidesTurn (exterior angle)Interior angle (180 − turn)
Equilateral triangle3120°60°
Square490°90°
Regular pentagon572°108°
Regular hexagon660°120°
Regular octagon845°135°

A common mistake is to turn by the interior angle. If you turn 60 degrees to draw a triangle, you get half a hexagon instead. The turtle turns by the exterior angle: the angle between the direction it was going and the direction it goes next.

Now you can write one program for every regular polygon:

import turtle
t = turtle.Turtle()
sides = int(input("How many sides? "))
length = int(input("How long is each side? "))
angle = 360 / sides
for side in range(sides):
    t.forward(length)
    t.left(angle)
turtle.done()

Type 100 sides of length 5, and the polygon looks just like a circle. That is how a computer draws a circle: as a polygon with very many very short sides.

Stars. A five-pointed star is drawn by turning 144 degrees at each point, five times. The turtle turns 5 × 144 = 720 degrees in total, which is two full turns: it goes round the centre twice.

t.color("gold")
t.fillcolor("yellow")
t.begin_fill()
for point in range(5):
    t.forward(150)
    t.right(144)
t.end_fill()

Colours. You can name colours, such as "red" , "orange" , "deep sky blue" or "gold" , or use the hex colour codes from Chapter 4, such as "#FF8000" for orange. For random colours, switch the screen to RGB numbers from 0 to 255:

import random
screen.colormode(255)
t.color(random.randint(0, 255), random.randint(0, 255), random.randint(0, 
255))

Moving without drawing. To draw shapes in different places, lift the pen, move, and put it down again:

t.penup()
t.goto(-150, 100)
t.pendown()
t.circle(40)

Forgetting penup() leaves a line across your picture from the old position to the new one. Every turtle artist has done this.

Patterns: loops plus a twist. Some of the most beautiful patterns come from repeating a shape while turning a little each time. This is how a rangoli or kolam pattern grows from a simple repeated motif:

import turtle
t = turtle.Turtle()
t.speed(0)
screen = turtle.Screen()
screen.bgcolor("black")
for petal in range(36):
    if petal % 3 == 0:
        t.color("magenta")
    elif petal % 3 == 1:
        t.color("gold")
    else:
        t.color("cyan")
    t.circle(100)
    t.left(10)
t.hideturtle()
turtle.done()

36 circles, each turned 10 degrees from the last: 36 × 10 = 360, a complete flower. The % operator from Chapter 7 cycles through three colours: petals 0, 3, 6 and so on are magenta; 1, 4, 7 are gold; 2, 5, 8 are cyan. The pattern has rotational symmetry, a topic from your maths book.

Spirals. If the distance grows each time round the loop, you get a spiral:

for step in range(150):
    t.forward(step * 2)
    t.left(91)

With a turn of exactly 90 degrees you would get a square spiral. Turning 91 degrees makes each square slightly twisted, and the spiral seems to rotate. Change 91 to 121, 61 or 145 and see what happens.

💡 Memoon’s tip: Plan a turtle drawing on squared paper first. Mark (0, 0) in the middle, then write down the coordinates of every corner. Drawing becomes a list of goto() commands, and you will not get lost.

Illustration from Byte by Byte Book 6: Chapter 9 – Drawing with Python Turtle

✍️ Try It Yourself

Activity 1: First shapes. Using a for loop each time, draw an equilateral triangle, a square, a pentagon and a hexagon, all with sides of 100. Use penup() and goto() so they do not overlap.

Activity 2: The polygon machine. Type the polygon program from this chapter. Try 3, 6, 10, 20 and 100 sides. At how many sides does it start to look like a circle? (You may need to make the side length smaller as the number of sides grows.)

Activity 3: A house. Draw a house: a filled square for the walls, a filled triangle for the roof (turn 120 degrees at each corner), a rectangle for the door and two small squares for windows. Plan the coordinates on squared paper first.

Activity 4: Starry sky. Make the background dark blue. Use a for loop that repeats 20 times. Each time, lift the pen, go to a random position with random.randint(-300, 300) and random.randint(-250, 250) , put the pen down, and draw a small filled yellow star.

Activity 5: Your own rangoli. Change the rangoli program: try squares or hexagons instead of circles, change the number of repeats and the turn (they must multiply to 360 for a complete pattern), and choose your own colours. Give your design a name.

Activity 6: Spiral explorer. Run the spiral program with different turn angles. Write down the angle and draw a quick sketch of what each produces. Which angles give five arms? Which give a smooth curve?

Unplugged: Be the turtle. Mark a starting point on the floor with chalk or tape and face a wall. A partner reads out turtle commands such as forward 4 (steps) and left 90 . Walk them out. Can you walk a perfect square? Now try a triangle. Did you remember to turn 120, not 60?

🎉 Memoon Solves It

They spent eight days practising. Kachui insisted on testing every program with a real turtle first: himself. He walked forward and turned on the sand while Memoon read out the commands, and when he walked half a hexagon instead of a triangle, they found the bug at once. (She had used the interior angle.)

Noodles discovered that if Memoon forgot penup() , he got long glowing lines across the wall to chase. He was disappointed when she stopped forgetting.

On the night of the Festival, the whole of Pearlhaven filled the square. Memoon ran her program. A tiny point of light appeared at the centre of the Glow Wall. It drew a golden circle, turned ten degrees, and drew another, and another, until a vast magenta, gold and cyan flower bloomed across the wall. Then came stars, hexagons, a spiral that seemed to twist forever, and finally, in glowing letters made from careful goto() lines, the word PEARLHAVEN.

The square erupted. Thousands of fish swirled in a cheering spiral of their own. Octavia wiped one eye with the tip of an arm.

Afterwards, the mayor of Pearlhaven, a stately old grouper, swam up to them. "Magnificent," he said. "But such a pity that only the fish could see it. For thirty years the rest of Memunic has forgotten we exist. I wish we could show everyone."

Memoon thought about the Light Bridges, carrying messages to every village. In Book 3 she had learned what a website was. She had never built one.

"Maybe we can," she said.

❓ Check Your Knowledge

  1. What must be at the top of every turtle program?
  2. What do t.penup() and t.pendown() do? Why would you need them?
  3. Write a for loop that draws a square with sides of 80.
  4. A turtle draws a regular polygon. What is the exterior angle for (a) 3 sides (b) 8 sides (c) 10 sides?
  5. A student wants to draw an equilateral triangle and turns 60 degrees each time. What will they get, and why?
  6. In turtle coordinates, where is the point (0, 0)? Which way does the y value increase?
  7. Which direction is the turtle facing after t.setheading(180) ?
  8. What do t.begin_fill() and t.end_fill() do?
  9. Why must you never call your own program turtle.py ?
  10. In the rangoli program, 36 circles are drawn with a turn of 10 degrees. If you wanted 24 circles in a complete pattern, what turn would you need?
  11. Predict the shape drawn by this code:
for i in range(6):
    t.forward(100)
    t.right(60)
  1. Challenge: Write a program that asks the user for a number of points and draws a star with that many points. (Hint: for an odd number of points n, try turning 180 - 180 / n degrees each time. Test it with 5, 7 and 9.)

📚 Word Bank

  • Turtle graphics: drawing by giving movement commands to an on-screen turtle carrying a pen.
  • turtle module: the Python module for turtle graphics.
  • Screen: the turtle drawing window.
  • Heading: the direction the turtle is facing, in degrees.
  • Regular polygon: a shape whose sides are all equal and whose angles are all equal.
  • Exterior angle: the angle the turtle turns at each corner; for a regular polygon it is 360 ÷ number of sides.
  • Interior angle: the angle inside a shape at a corner.
  • Fill: colouring in the inside of a closed shape.
  • Rotational symmetry: a pattern that looks the same after being turned by a certain angle.
  • Rangoli (kolam): a traditional Indian pattern made from repeated, symmetrical shapes.

Keep learning with Byte by Byte

Explore Book 6: Python, Data and How Computers Work. Find the ebook, purchase details and teaching slides on MemuniCity.

Watch this chapter on YouTube

Comments

Popular posts from this blog

CA-7 Job Status and Failure Reason Codes

Here are the various status codes that You may see for jobs in the Queue or Logs in CA-7. R-C0002 R-C0003 R-C0099 R-C0255 R-JCLER A-U0002 A-U0004 A-U0015 A-U0043 A-U4095 A-SOC7 A-U4000 Reason Code/Job Status Code explanation: The indication of the job's current disposition. Values and their meanings are: A-Snnnn-- The job has failed with a system abend. A-Unnnn --The job has failed with a user abend. C-Cnnnn --The job has completed successfully and is going through completion processing. E-ARFATT-- An error occurred during the attempt to attach ARF definitions. This can result if the ARFSET specified is not defined. A diagnostic message may have been written to the CA-7 log, the OS console, or to the trailer queue for the job (in which case it can be displayed using LQ,JOB=x,LIST=ALL). E-ARFERR ---The job encountered an error in the ARF processing. Do a LARFQ command for the job to get more specific information. E-SEGERR --The job has been requeued...

Whistling Winds and Waterfalls: 4 Days of Magic in Shillong

Nestled in the clouds, where the scent of pine trees mingles with the rhythm of waterfalls and the tunes of local guitar-strumming youth—Shillong is more than a place. It’s a vibe. If you’ve got 3 nights and 4 days, you’ve got just enough time to fall in love. Here’s how to make the most of it—food, fun, fog and fantastic views included. Day 1: Shillong, We’re Coming for You! You land in Guwahati, barely out of the airport when the hills start calling. You hop into your cab, Spotify on, windows down, and the three-hour ride to Shillong begins. Just when you think it can’t get better, you stop at Umiam Lake —a lake so calm, it looks like someone ironed the water. By evening, you’re sipping hot chai in Laitumkhrah, maybe nibbling on spicy momos or pork jadoh from a roadside stall. You’re checked into your charming hotel ( Tripura Castle if you fancy old-world royalty, Ri Kynjai if you’re into lakeside poetry). The breeze whispers secrets of waterfalls and pine forests. Sleep well, drea...

Installing and Configuring Hadoop on Ubuntu as a Pseudo Distributed Single Node Cluster

Briefly what is psuedo-distributed single node Hadoop cluster: It is a Hadoop distributed cluster having Single Node. All the five daemons (NN,DN,JT,TT,SNN) are running as individual JVM (java process) instances. We will get all distributed features of Hadoop. This mode is used to develop, test, and staging (before production) Map Reduce programs quickly. It writes all the system, daemon and user logs to different files on the cluster To install Hadoop in this mode, we have to modify the hadoop-env.sh, core-site.xml, hdfs-site.xml, mapred-site.xml. hadoop-env.sh contains all the Environment variables which are required for running Hadoop. All the default values are fine, Only we have to modify the JAVA_HOME=“The location of Java Home Directory” Core-site.xml contains all the cluster specific information like io, temp directory, sorting, file system uri etc. Hdfs-site.xml contains all the parameters which are specific to HDFS like name node directory, data node directory...