Reputation: 53
I am trying to create a loop that takes an input by a user and draws however many squares but it increases the size of the squares with each loop, however 2 sides are stay connected. I'll include the graphic to better explain.
import turtle
squares = 1
while squares >= 1:
squares = int(input('How many squares would you like drawn?:'))
if squares == 0:
print("You must have at-least 1 square.")
squares = int(input('How many squares would you like drawn?:'))
else:
for count in range(squares):
turtle.forward(30)
turtle.left(90)
turtle.forward(30)
turtle.left(90)
turtle.forward(30)
turtle.left(90)
turtle.forward(30)
turtle.left(90)
turtle.done()
Upvotes: 1
Views: 7755
Reputation: 41872
While waiting for @ReblochonMasque's solution to finish drawing 100 squares, there's plenty of time to implement an alternate, faster solution based on stamping.
The first thing to note is in the provided instructions it says to draw 100 squares to create the design in the figure, but that figure consists of just under 50 squares. It's also been scaled in some non integral fashion which makes it appear to have different line thicknesses.
Let's focus on the spirt of the problem rather than the example. The OP had a 1 square minimum so I've preserved that. This solution also naturally tends to center the square on the window:
from turtle import Turtle, Screen
DELTA = 3
MINIMUM = DELTA * 2
CURSOR_SIZE = 20
num_squares = -1
while num_squares < 1:
try:
num_squares = int(input('Input the number of squares: '))
except ValueError:
print("please enter an integer.")
if num_squares < 1:
print("You must have at least 1 square.")
screen = Screen()
turtle = Turtle("square", visible=False)
turtle.fillcolor("white")
for size in range(((num_squares - 1) * DELTA) + MINIMUM, MINIMUM - 1, -DELTA):
turtle.goto(turtle.xcor() + DELTA/2, turtle.ycor() - DELTA/2)
turtle.shapesize(size / CURSOR_SIZE)
turtle.stamp()
screen.exitonclick()
This is clearly not the kind of solution the OP was looking for, but maybe next time a problem like this comes up, it might be one the OP will at least consider.
Upvotes: 1
Reputation: 36662
The input request and the drawing logic ought to be separated.
Here is one approach that returns the turtle at the start at each turn, after increasing the side length.
import turtle
num_squares = 3
t = turtle.Turtle()
t.pendown()
side = side_unit = 30
while True:
try:
num_squares = int(input('input the number of squares'))
except ValueError:
print("please enter an integer")
if num_squares > 3:
break
for sq in range(1, num_squares + 1):
t.left(90)
t.forward(side)
t.left(90)
t.forward(side)
t.left(90)
t.forward(side)
t.left(90)
side = side_unit + 3 * sq # increase the size of the side
t.goto(0,0) # return to base
turtle.done()
Upvotes: 1