Drawing Shapes Using Turtle
-
01-07-2021 - |
Question
I'm trying to use Python/Turtle to achieve a result like this:
I drew the squares uneven in paint but I mean for them to be even. The squares can be any shape as well depending on the user input (for ex. 5 for polygons).
Here is my code so far:
import turtle
import time
import random
print ("This program draws shapes based on the number you enter in a uniform pattern.")
num_str = input("Enter the side number of the shape you want to draw: ")
if num_str.isdigit():
squares = int(num_str)
angle = 180 - 180*(squares-2)/squares
turtle.color(random.random(),random.random(), random.random())
turtle.begin_fill()
count = 0
x = -80
y = -80
turtle.setpos(x,y)
turtle.down()
while count < 8:
x += 50
y += 50
turtle.goto(x,y)
for i in range(squares):
count += 1
turtle.forward(20)
turtle.left(angle)
turtle.forward(20)
print (turtle.pos())
turtle.end_fill()
time.sleep(15)
turtle.bye()
And here is what I get:
The error I get is: How can I get it to print out 8 shapes total, instead of only 2, I though the loop would make it repeat 8 times because of the count += 1 < 8?
I thought the loop would change the position of x and y by adding 50, 50 each time and then I would tweak it to give the right coordinates to make the shape I want, but it won't even display all 8 yet?
I've spent a while reconfiguring the code but instead of doing trial and error forever, I figured maybe some help would work, thanks.
I am using Python 3.2.3
La solution
If you choose to display a shape with four sides, you're only going to draw two shapes. This is because you're increasing your loop counter once per side for each shape.
This is not a good way to do loops, counters are rarely necessary, and when they are - use enumerate
You want to try something like this.
numshapes = 8
for x in range(numshapes):
x += 50
y += 50
turtle.goto(x,y)
for i in range(squares):
turtle.forward(20)
turtle.left(angle)
turtle.forward(20)
print (turtle.pos())