Introduction
Python Turtle is a fun and interactive way to draw shapes and patterns using simple commands. In this tutorial, we will learn how to draw basic shapes like squares, circles, triangles, and polygons using Python’s Turtle Graphics module. This is an excellent project for beginners who want to explore programming with visual elements while understanding loops and angles.
Prerequisites
Before you begin, make sure you have Python installed on your system. Turtle Graphics comes pre-installed with Python, so no additional libraries are required.
Setting Up the Turtle
First, we need to import the turtle
module and set up our drawing environment.
import turtle
def draw_square(size):
for _ in range(4):
turtle.forward(size)
turtle.right(90)
def draw_circle(radius):
turtle.circle(radius)
def draw_triangle(size):
for _ in range(3):
turtle.forward(size)
turtle.left(120)
def draw_polygon(sides, length):
angle = 360 / sides
for _ in range(sides):
turtle.forward(length)
turtle.right(angle)
# Set up the turtle
screen = turtle.Screen()
screen.bgcolor("white")
turtle.speed(3)
# Draw shapes
turtle.penup()
turtle.goto(-100, 100)
turtle.pendown()
draw_square(100)
turtle.penup()
turtle.goto(100, 100)
turtle.pendown()
draw_circle(50)
turtle.penup()
turtle.goto(-100, -100)
turtle.pendown()
draw_triangle(100)
turtle.penup()
turtle.goto(100, -100)
turtle.pendown()
draw_polygon(6, 60) # Hexagon
turtle.hideturtle()
turtle.done()
Explanation
1. Drawing a Square
- The
draw_square(size)
function moves the turtle forward and turns it right by 90 degrees four times to form a square.
2. Drawing a Circle
- The
draw_circle(radius)
function uses Turtle’s built-incircle(radius)
method to draw a perfect circle.
3. Drawing a Triangle
- The
draw_triangle(size)
function moves forward and turns left by 120 degrees three times to complete an equilateral triangle.
4. Drawing a Polygon
- The
draw_polygon(sides, length)
function divides 360 degrees by the number of sides to calculate the turning angle, ensuring a proper polygon shape.
5. Turtle Movement and Positioning
- We use
penup()
andpendown()
to move the turtle without drawing, ensuring shapes are positioned correctly on the screen. - The
goto(x, y)
function places the turtle at specified coordinates before drawing each shape.
Running the Code
Save the script as draw_shapes.py
and run it in a Python environment. You will see a square, circle, triangle, and hexagon drawn on the screen.
Conclusion
By following this tutorial, you have learned how to: ✅ Use Python Turtle for drawing various shapes ✅ Implement loops to create geometric figures efficiently ✅ Control turtle movement and positioning ✅ Customize the drawing speed and layout
This project is a great way to understand basic graphics programming while having fun with Python! 🎨🐢
Additional Resources
- Video Tutorial:
If you found this tutorial helpful, don’t forget to like, comment, and share! Subscribe to Madras Academy for more exciting coding tutorials! 🚀🔥