Monday, April 21, 2025

Python Turtle - For Loop & While Loop

Turtle for loops can provide interesting results, like circles inside circles using dedicated circle() method: 

import turtle

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

for x in range(20, 50):
    t.circle(x * 2)


 

Change of object orientation can be fun experiment:

import turtle

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

for x in range(20, 50):
    t.circle(x * 2)
    t.left(180)
    t.circle(x * 2)
    t.right(90)


 

And we can get same or similar results with while loops. But sometimes that demands a little bit more thinking:

import turtle

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

n = 20

while n < 50:
    t.circle(n * 2)
    t.left(180)
    t.circle(n * 2)
    t.left(90)
    n = n + 1

Definitely check YouTube tutorial on Turtle For and While Loops.

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 .  ...