Monday, April 21, 2025

Python Turtle - For Loop, Turtle Speed, Circle, Dot

We can set movement of turtles using for loops, it's easy: For every pass, a turtle will go forward for 200 pixels than turn left for 90 degrees:

import turtle

t = turtle.Turtle()

for x in range(4):
    t.fd(200)
    t.left(90)


 

There is a lot of possibilities to play around with shapes. In this one we are also using method speed(). Range for for loop is large enough to paint black ring.

A turtle (arrow, object) will go forward for 200 pixels than rotate left for 90 * 1.01. You can play around with values to get different shapes.

End turtle position is not hidden, that's why we see a small black triangle:

import turtle

t = turtle.Turtle()
t.speed(0)

for x in range(400):
    t.fd(200)
    t.left(90 * 1.01)


 

We can set color for lines and have variable pc = 1.05 set outside for loop. We are also hiding a turtle after movement is done:

import turtle

t = turtle.Turtle()
t.speed(0)
t.color("red")

pc = 1.05

for x in range(250):
    t.fd(200)
    t.left(90 * pc)

t.hideturtle()


 

It is simple to get circles inside circles. Just use higher values one after another for circle() method:

import turtle

t = turtle.Turtle()

t.circle(30)
t.circle(60)
t.circle(120)
t.circle(240)

t.hideturtle()


 

We can use dot() method in combination with for loop to get simple animation:

import turtle

t = turtle.Turtle()
t.speed(0)

t.color("red")
t.dot(50)

for x in range(50):
    t.fd(200)
    t.bk(200)
    t.left(45)

t.hideturtle()


You can check corresponding YouTube tutorial on For Loop, Turtle Speed, Circle, Dot.

No comments:

Post a Comment

Tkinter Introduction - Top Widget, Method, Button

First, let's make shure that our tkinter module is working ok with simple  for loop that will spawn 5 instances of blank Tk window .  ...