Python Circle Sector Challenge

Maths and Computer Science are often taught very separately, and yet they make excellent companions. Writing a program to explore a topic from Maths can really help to understand the topic deeply as well as providing a great opportunity to practice your coding skills.

Python Program to Draw a Circle Sector

Here’s a challenge: use the Python Turtle Module as described here, to draw a sector of a circle given a radius and an angle. The result should look something like this:

Online Python lessons - circle sector

Here’s some skeleton code to get you started:

import turtle

# Set up Turtle and window
turtle.setup(500, 500)  # Determine the window size
wn = turtle.Screen()  # Get a reference to the window
wn.title("Circle Sectors")  # Change the window title
wn.bgcolor("lightgreen")  # Set the background color
bob = turtle.Turtle()  # Create our favorite turtle
bob.color("hotpink")


def draw_sector(angle, radius, t):
    pass


# Try out the function, giving an angle, a radius and the name of your turtle
draw_sector(40, 100, bob)

# Allow click to exit
turtle.done()

You might want to check out turtle.setheading() and turtle.circle() from the docs to get some extra help.

Solution to Python Circle Sector Challenge

Here’s a possible solution for this challenge:

There’s actually quite a bit going on in that code, and depending on your level of experience, some of it might require further exploration. Here’s a few key points:

  • Creating a turtle.Screen() object to get access to things like bgcolor, title etc.
  • Passing in a turtle as a function argument. This is often good practice as it leads to clean, well-organised code.
  • begin_fill() and end_fill() are fun turtle methods to play with
  • setheading() can you determine what system of measuring angles is used by Turtle Graphics? 90° is actually North, and rotation increases in an anti-clockwise direction.

I hope you enjoyed this challenge. Happy computing.

Sharing is caring!

Leave a Reply

Your email address will not be published. Required fields are marked *