Skip to content
Sign upLog in
← Back to Community

How do you draw a triangle in pyhton turtle using for loops?

Profile icon
AhmadShaheerSha

import turtle
def drawing_circle():
bob.color("Green")
bob.speed(1000)
bob.shape("turtle")
bob.circle(59)
window = turtle.Screen()
bob = turtle.Turtle()
bob.goto(50,-30)
bob.pendown()
drawing_circle()

turtle.color("Green")
turtle.fillcolor("Yellow")
turtle.speed(1000)
def recursive_triangles(length,depth):
turtle.begin_fill()
if depth == 0:
for i in range(0,3):
turtle.forward(length)
turtle.left(120)
else:
recursive_triangles(length/2, depth-1)
turtle.forward(length/2)
recursive_triangles(length/2,depth-1)
turtle.backward(length/2)
turtle.left(60)
turtle.forward(length/2)
turtle.right(60)
recursive_triangles(length/2, depth-1)
turtle.left(60)
turtle.backward(length/2)
turtle.right(60)
turtle.end_fill()
window = turtle.Screen()
t = turtle.Turtle()
recursive_triangles(100,2)

So this is my code but how do I use for loops to make this more efficient? Also is there a way to put the two functions together and make one function?

Voters
Profile icon
AhmadShaheerSha
Comments
hotnewtop
Profile icon
Geocube101

I shall happily give you this function:

def generatePolygon(rot=0, length=100, sideCount=3, speed=0, filled=False, output=True): t.showturtle() t.speed(speed) rot = int(rot) sideCount = int(sideCount) rotate(rot) c = 360 / sideCount if filled == True: t.begin_fill() for a in range(sideCount): t.forward(length) t.left(c) if filled == True: t.end_fill() t.hideturtle() if output == 1 or output == True: print("Generated Polygon with Side a Count of: " + str(sideCount) + "\n")

Basically, this function takes 360 and divides it by the side count which gives the angle of rotation required, though it does get buggy once you try to generate things with more than 10 sides.


Anyway, for a simple for loop:

t = Turtle() #Create Turtle for a in range(3): t.forward(side_length) #Move turtle forward t.left(120) #Rotate turtle (120 = 360 / 3 == triangle)

"side_length" is an integer > 0

Profile icon
ColePayneSexton

Hey

@Geocube101
, how do you add code blocks, i followed the markdown instructions but it didn't work.

Profile icon
Geocube101

@plant3jyyehejy

Three of these "`" followed by the language extension
So for python it would be "```py"
And then another three to close the block

Profile icon
ColePayneSexton

So

This_is_a_test = 5 Print(this_is_a_test)

@Geocube101

Profile icon
Geocube101

@plant3jyyehejy

Yeah

Profile icon
ColePayneSexton

Cool thanks

@Geocube101

Profile icon
ColePayneSexton

You could make your turtle
turtle.forward(100)
Turtle.left(45)
Turtle.Forward(100)
Turtle.left(45)
Turtle.forward(100)

This is for non-right angle triangles