Solutions 2.3: Turtle Stars
Let’s review together the solutions to the exercises from Lesson 2.3: Turtle Stars.
Before you look at the answers below, please try to solve all the problems by yourself. We are hoping that you will use the solution pages only to check your work or to get help after you have been stuck for a while.
Exercise 1
Using Turtle Graphics, draw a star with n vertices, where n is odd.
Solution
First, we create a new file generic_star_odd.py and save it in the Unit2 folder. We use two variables: n, for the number of vertices the star will have, and angle, for the outer angle the turtle must turn to draw the star. The inner angle for an n-point star (when n is odd) is 180°/n. This means that the outer angle is 180°-180°/n. That’s all we need to draw an n-point star.
from turtle import *
hideturtle()
penup()
backward(100)
pendown()
n = 15
angle = 180 - 180 / n
for i in range(n):
forward(200)
right(angle)
And we can easily draw a 45-point star by just changing the value of n to 45.
from turtle import *
hideturtle()
penup()
backward(100)
pendown()
n = 45
angle = 180 - 180 / n
for i in range(n):
forward(200)
right(angle)
[cws-ad1]
Exercise 2
Implement a Python program that will use the Turtle Graphics module and draw a star with 2*n vertices, where n is even.
Solution
Similarly as in Exercise 1, we create a new file generic_star_even.py and save it in the Unit2 folder. We use two variables: n, for one half of the vertices the star will have, and angle, for the outer angle the turtle must turn to draw the star. The inner angle for a 2n-point star (when n is even) is 180°/n. This means that the outer angle is 180°-180°/n. The code is very similar to Exercise 1.
from turtle import *
hideturtle()
penup()
backward(100)
pendown()
n = 4
angle = 180 - 180 / n
for i in range(2*n):
forward(200)
right(angle)
Here is an 8-point star (using n = 4).
And here is a 36-point star (using n = 18).
[prev-next-ad1 prev=”https://codewithsara.com/python-with-sara/python-101/u2-python-turtle-graphics/u2s2-turtle-programming/” next=”https://codewithsara.com/python-with-sara/python-101/u2-python-turtle-graphics/u2s4-coloring-with-turtle/”]