I tried making concentric squares in python with a while

Viewed 430

I want to make a code for concentric squares using python 3 and the while statement, but couldn't quite get it right. A little help? Thanks! Okay, here is my attempt:

import turtle

t = turtle.Turtle()

x=0
y=0
z=0
a=-0
b=0
c=-0
d=0
e=0


while x < 100:
  t.pendown()
  x=x-10
  y=y+10
  t.goto(x,y)
  z=z-10
  a=a-10
  t.goto(z,a)
  b=b+10
  c=c-10
  t.goto(b,c)
  d=d+10
  e=e+10
  t.goto(d,e)
  t.setposition(x,y)
  
  
turtle.done()

I wanted to use a while for this, so yeah... Thanks!

4 Answers

You need to use penup and pendown to stop and start painting a trail.

import turtle

t = turtle.Turtle()

x=0
y=0
z=0
a=-0
b=0
c=-0
d=0
e=0


while x < 100:
    t.penup()
    x=x-10
    y=y+10
    t.goto(x,y)
    t.pendown()
    z=z-10
    a=a-10
    t.goto(z,a)
    b=b+10
    c=c-10
    t.goto(b,c)
    d=d+10
    e=e+10
    t.goto(d,e)
    t.setposition(x,y)

turtle.done()

You are almost there, just add a penup:

while x < 100:
   t.penup()         # <- penup here
   x=x-10
   y=y+10
   t.goto(x,y)
   z=z-10
   a=a-10
   t.pendown()       # <- pendown here
   t.goto(z,a)
   b=b+10
   c=c-10
   t.goto(b,c)
   d=d+10
   e=e+10
   t.goto(d,e)
   t.setposition(x,y)
  
  
   turtle.done()

Perhaps a cleaner way:

import turtle

squares = 5 # Choose how many squares
scale = 20 # Chose the scale of the squares

t = turtle.Turtle()
for i in range(squares+1):
    for _ in range(4):
        t.pendown()
        t.forward(scale*i)
        t.right(90)
    t.penup()
    t.setpos(t.xcor()-scale/2,t.ycor()+scale/2)

turtle.done()

Output:

turtle-graphics

Just for fun, an alternate approach using a (single) for loop and stamping instead of drawing:

from turtle import Screen, Turtle

SQUARES = 10

screen = Screen()

turtle = Turtle()
turtle.hideturtle()
turtle.shape('square')
turtle.fillcolor('white')

for size in range(SQUARES, 0, -1):
    turtle.shapesize(size)
    turtle.stamp()

screen.exitonclick()

enter image description here

Should be significantly faster. Another example of better living through stamping.

Related