#Advanced Loops on Python with Turtle!
In this tutorial, you shall learn about the wonders of loops on Python with Turtle. Let's delve into how you can use them!
Just don't forget to start of with this code:
import turtle wn=turtle.Screen() wn.bgcolor("Red") #Change this to any color you would like. t=turtle.Turtle() t.speed(0)
As shown in the example below, a square would be drawn like this.
for x in range(4): t.forward(70) #Forward may be any number. t.right(90) # Angle has to stay the same but you may use left or right.
If you would like to use a more advanced take on this , define it so you don't have to write it out again! You do this with this code:
def square(): for x in range(4): t.forward(70) t.right(90)
Defining a function makes it easier for us to create a "Stamp" for a shape. There is always an easy way to find out how to print a regular polygon. This means that regular shapes with 3 sides or more will follow this pattern.
Equilateral Triangle: 3 Sides, 120 degree turns on python w/Turtle.
Square:4 sides,90 degree turn on python w/ Turtle.
Regular Pentagon:5 sides . 72 degree turn on python w/Turtle.
There is a pattern to this though. Let me show you.
The interior angles of the triangle equal 180 degrees. The turtle however relies on exterior angles. Therefore, 180 divided by 3 =60 Then, the exterior angles of a shape equal 180-interior angle, which equals 120.
The interior angles of a square= 360 360 divided by 4=90. 180-90=90. The same pattern occurs with pentagons. The rule is, as one more side is added, 180 degrees are added to the total of the interior angles. Therefore, a hexagon would be 60 degrees right, due to the fact that 720 (540+180) divided by 6=120. Then,180 minus 120=60
To challenge yourself, find the code for a decagon.
####Loops which don't repeat the same shape!
In Python and Python with Turtle, there is a function in which we can vary the output of the loop by using:
for x in range():
You may be asking how, and I shall show you!
Start by running the code in this link:
Did you see that? It was all a loop. Down below is code which perfectly demonstrates a cool loop in action.
for x in range(360): t.forward(5) t.right(x+180)
This works, because x represents the term. It is like the nth term in maths! The code works by going forward 5, and then going (Term)+180 degrees. It creates a cool spiral effect twice!
My other code that I linked earlier went like this:
for x in range(360): t.forward(x+1) t.right(x+1) This means that is starts of as a reasonably small number, starting with 1 and going up to 361 (1 degrees, technically speaking)on both fronts. It makes a slowly inward spiralling pattern which expands. Please check the example below for some examples of loops. I hope you have enjoyed this tutorial! If you find any other cool loops, be sure to comment them down below and I'll take a look!