Free

3: Building Our First Programs

⏱️ 45-60 minutes
📊 intermediate

Chapter 13: "Drawing with Code"

At the next meeting, Professor Bit met Alice with a mysterious smile.

— Today we'll be doing art, — he announced, pointing to a large monitor in the center of the room.

— Art? — Alice was surprised. — But aren't we studying programming?

— Programming and art are quite compatible, — the Professor replied. — Today we'll draw with code!

Byte joyfully jumped and displayed a colorful pattern of geometric shapes on his screen.

— For creating graphics with code, we'll use the Turtle library, — the Professor explained. — It's a simple but powerful drawing tool.

He paused for a moment and quietly read:

В рисунке — отпечатки эволюций,
В строке — звучанье древней глубины.
Витиеватость творческих конструкций
Приносит в код дыханье новизны.

И так плетёт фракталы мирозданье,
Ведя беззвучный, вечный диалог.
Творя, пока не кончится дыханье,
Мы в вечности проводим рода ток.

Любой куплет однажды спетой песни
Спет голосами тех, кто был до нас.
Их делая полней и интересней,
Мы сохраняем их для новых рас.

The Professor typed the first lines of code:

python
import turtle

Create canvas and brush


canvas = turtle.Screen()
canvas.bgcolor("white") # White background
brush = turtle.Turtle()
brush.shape("turtle") # Turtle shape
brush.color("blue") # Blue color
brush.pensize(2) # Line thickness

Draw a square


for _ in range(4):
brush.forward(100) # Move forward 100 steps
brush.right(90) # Turn right 90 degrees

canvas.exitonclick() # Close window on click

A window with a white background appeared on the screen, on which a blue turtle drew a square.

— Wow! — Alice exclaimed. — The turtle really drew a square!

— The Turtle library works on the principle of "turtle graphics," — the Professor explained. — You control a "turtle" that leaves a trail when it moves. It's like if you were drawing with a pencil on paper.

— What does the underscore in for _ in range(4) mean? — Alice asked.

— Good question! — the Professor nodded. — The underscore (_) is used when we don't care about the loop variable. We just want to repeat the action 4 times, and we don't need to know the current iteration number.

— Let's draw something more complex! — Alice suggested.

— Of course! How about a colorful spiral? — The Professor wrote new code:

python
import turtle
import random

canvas = turtle.Screen()
canvas.bgcolor("black") # Black background
brush = turtle.Turtle()
brush.speed(0) # Maximum speed

List of colors for the spiral


colors = ["red", "orange", "yellow", "green", "blue", "purple"]

Draw spiral


for i in range(360):
brush.color(random.choice(colors)) # Random color
brush.forward(i * 0.01 + 1) # Increase step
brush.right(10) # Turn 10 degrees

canvas.exitonclick()

A colorful spiral shimmering with all the colors of the rainbow appeared on the black background.

— This is incredibly beautiful! — Alice admired. — What does brush.speed(0) mean?

— This sets the maximum movement speed of the turtle, — the Professor explained. — Values can be from 1 (slowest) to 10 (fast). A value of 0 means the movement animation is disabled, and the turtle draws instantly.

— Can we draw something that looks more like a real drawing? — Alice asked.

— Yes, you can create quite complex drawings, — the Professor nodded. — Let's draw a flower:

python
import turtle
import math

canvas = turtle.Screen()
canvas.bgcolor("skyblue")
brush = turtle.Turtle()
brush.speed(0)

Draw stem


brush.color("green")
brush.pensize(5)
brush.penup()
brush.goto(0, -200)
brush.pendown()
brush.left(90)
brush.forward(200)

Draw flower center


brush.color("brown")
brush.penup()
brush.goto(0, 0)
brush.pendown()
brush.begin_fill()
brush.circle(20)
brush.end_fill()

Draw petals


brush.color("pink")
for i in range(12):
brush.penup()
brush.goto(0, 0)
brush.pendown()
brush.setheading(i 30) # Turn 30 i degrees

# Draw petal
brush.begin_fill()
for j in range(60):
brush.forward(2)
brush.left(3)
brush.end_fill()

Hide turtle and finish


brush.hideturtle()
canvas.exitonclick()

A flower with pink petals, a brown center, and a green stem appeared on the sky blue background.

— This is beautiful! — Alice exclaimed. — But the code became much more complex.

— Yes, here we used several new commands, — the Professor agreed. — For example:

  • goto(x, y) moves the turtle to the specified coordinates

  • penup() and pendown() allow lifting and lowering the "pen" to move without drawing

  • beginfill() and endfill() fill the area inside the drawn contour with color

  • setheading() sets the turtle's direction

  • hideturtle() hides the turtle so it doesn't spoil the drawing
  • Logic, observing the process, added:
    — In programming graphics, we often use mathematics. Coordinates, angles, distances — all of these are mathematical concepts.

    — Can we create animations? — Alice asked.

    — Of course! — the Professor replied. — Let's create a simple animation of a moving sun:

    python
    import turtle
    import time

    canvas = turtle.Screen()
    canvas.bgcolor("lightblue")
    canvas.setup(600, 400) # Window size

    Create sun


    sun = turtle.Turtle()
    sun.shape("circle")
    sun.color("yellow")
    sun.penup()
    sun.goto(-300, 0) # Initial position on the left

    Create ground


    ground = turtle.Turtle()
    ground.penup()
    ground.goto(-300, -100)
    ground.pendown()
    ground.color("green")
    ground.pensize(3)
    ground.forward(600) # Ground line
    ground.hideturtle()

    Sunrise and sunset animation


    for x in range(-300, 301, 5):
    y = 100 (1 - ((x / 150) * 2)) # Parabola for trajectory
    sun.goto(x, y)
    time.sleep(0.05) # Pause to create animation

    canvas.exitonclick()

    An animation appeared on the screen: a yellow sun slowly rose above the green horizon line, then set.

    — This is already a real animation! — Alice admired. — We use a loop so the sun moves along a parabola from the left edge to the right.

    — Another interesting application of programming in graphics is fractals, — said the Professor. — Fractals are geometric shapes that repeat their structure at different scales.

    — Sounds complicated, — Alice frowned.

    — Actually, they're quite simple to create using recursive functions, — the Professor smiled. — Look:

    python
    import turtle

    canvas = turtle.Screen()
    canvas.bgcolor("black")
    brush = turtle.Turtle()
    brush.color("green")
    brush.speed(0)

    Recursive function for drawing a branch


    def draw_branch(turtle, length, level):
    if level == 0:
    return

    turtle.forward(length)

    turtle.right(30)
    draw_branch(turtle, length * 0.7, level - 1)

    turtle.left(60)
    draw_branch(turtle, length * 0.7, level - 1)

    turtle.right(30)
    turtle.backward(length)

    Set initial position


    brush.penup()
    brush.goto(0, -200)
    brush.left(90)
    brush.pendown()

    Draw fractal tree


    draw_branch(brush, 100, 6)

    brush.hideturtle()
    canvas.exitonclick()

    An elegant fractal tree with many branches appeared on the screen.

    A turtle draws a fractal tree

    — This is amazing! — Alice exclaimed. — How does it work?

    — The draw_branch function calls itself, creating smaller branches at the end of each branch, — the Professor explained. — The level parameter determines how many times this branching will occur. When level reaches zero, the recursion stops.

    — Nature also has many fractals, — Logic noticed. — Trees, snowflakes, fern leaves, blood vessel systems — all have fractal structure.

    — Computer graphics is a vast field, — the Professor summarized. — From simple geometric shapes to complex 3D models and animations. And all of this is created with code!

    — Now I understand that programming isn't only solving problems and processing data, but also creativity, — said Alice. — It's like magic: write a few lines of code, and a beautiful drawing appears!

    Task

    Come up with and describe what drawing you would like to create with code. It can be anything: an animal, a plant, a geometric pattern, or an abstract composition. How would you use basic commands (movement, turns, colors) to create your drawing? Make a sketch on paper and think about what loops or functions could help draw repeating elements.