so I'm working on a program where i want the output to have 4 triangles with the lengths 20,40,60,80 placed vertically where the top of each triangle should be exactly halfway along the baseline of the triangle above.
I have managed to get the first two triangles correct but cannot get the top two to align the way I want. I know I am going wrong somewhere but i cannot seem to see it
from turtle import *
NUMBER_OF_SHAPES = 4
for shape in range(1, NUMBER_OF_SHAPES + 1):
#Draw a Triangle
for sides in range(3):
forward(20 * shape)
left(120)
#Move forward to start position of next triangle
penup()
left(120)
forward(20 * shape)
right(120)
pendown()
from turtle import *
import time
NUMBER_OF_SHAPES = 4
for shape in range(1, NUMBER_OF_SHAPES + 1):
#Draw a Triangle
for sides in range(5): #redraw some edges to place the cursor on the top
forward(20 * shape)
left(120)
#Move forward to start position of next triangle
penup()
right(60)
forward(10 * (shape+1)) # half of the size of the next triangle
right(180)
time.sleep(0.5)
pendown()
Think outside the triangle:
from turtle import *
for length in range(20, 100, 20):
penup()
sety(length + ycor())
pendown()
circle(-2*length/3, steps=3)
hideturtle()
exitonclick()
Here were using turtle's circle() method to achieve two goals, first to draw a triangle, steps=3, and second to draw centered triangles starting from their top point by using a negative radius. Beyond that we simply need to adjust the vertical position.
As far as your code, I believe the problem is simpler than you're trying to make it. Things get easier if we start by moving forward half the length of the triangle, and then build from there:
from turtle import *
NUMBER_OF_SHAPES = 4
for shape in range(1, NUMBER_OF_SHAPES + 1):
forward(10 * shape)
for _ in range(4):
left(120)
forward(20 * shape)
right(120)
exitonclick()
This, in combination with reversing the order of the steps in the loop, and increasing iterations to 4, leaves us centered for the next triangle.
Related
I'm trying to get this code to request an input: number of points on a star, then use the turtle module to draw each respective star. Each one is meant to be in a distinct location and have a distinct line and fill color. This code won't draw second and third stars, though it'll draw the first one fine. Also, the fill function only fills the "arms" of the star, not the body. I'm attaching some code and a screenshot of when I tried it with the three inputs: 5, 7, and 9.
from turtle import *
def start():
"""This function initializes the window and the turtle.
Do not modify this function.
"""
setup(564, 564)
width(7)
side_length = 60 # Also the radius of a circle enclosed by the star.
penup()
goto(0, -side_length) # Start at the bottom of the star.
pendown()
def main():
points = int(input('How many points would you like on your star? '))
A = 360 / points
B = 2 * A
x = 0
side_length = 60
while x < points:
color('blue', 'red')
begin_fill()
left(A)
forward(side_length)
right(B)
forward(side_length)
x += 1
end_fill()
penup()
goto(2*side_length, 2*side_length)
pendown()
points = int(input('How many points would you like on your star? '))
while x < points:
color('green', 'yellow')
begin_fill()
left(A)
forward(side_length)
right(B)
forward(side_length)
x += 1
end_fill()
penup()
goto(-2*side_length, 2*side_length)
pendown()
points = int(input('How many points would you like on your star? '))
while x < points:
color('orange', 'purple')
begin_fill()
left(A)
forward(side_length)
right(B)
forward(side_length)
x += 1
end_fill()
# Do not change anything after this line.
if __name__ == '__main__':
start()
main()
done()
I hope someone can enlighten me on this one! I am very, very new to python and can't get my head around this one! Can you please help/explain...
I believe the following code should draw 4 squares in a row. This exercise is to learn nested loops. What it seems to be doing is to draw 4 squares on the same spot without moving forward to draw them next to each other on the same line.
# Draw Squares across page
from turtle import *
number_of_shapes = 4
for number_of_shapes in range(1, number_of_shapes + 1) :
# Draw a Square
for sides in range (1, 5) :
forward (40)
right (90)
# Move forward to start of next square
penup ()
forward (50)
pendown ()
The following works. Is there something wrong with your indentation?
#Draw Squares across page
from turtle import *
number_of_shapes = 4
for number_of_shapes in range(1, number_of_shapes + 1):
#Draw a Square
for sides in range(1, 5):
forward(40)
right(90)
#Move forward to start of next square
penup()
forward(50)
pendown()
My guess is that your code was this:
#Draw Squares across page
from turtle import *
number_of_shapes = 4
for number_of_shapes in range(1, number_of_shapes + 1):
#Draw a Square
for sides in range(1, 5):
forward(40)
right(90)
#Move forward to start of next square
penup()
forward(50)
pendown()
So rather than drawing the square and then moving, you're drawing a line and then moving.
The solution you wrote looks fine, maybe there is a problem with indentation which is most important in Python because it present code blocks like other languages do with {}. Another thing is, that your are using number_of_shapes in the first loop as iteration variable which can cause a problem since the loop save the number (1, 2, 3, 4, ...) to this variable. You can try how it works in a simple loop.
for x in range(1, 5):
print(x)
Try to change this to some different variable (for x in range(1, number_of_shapes + 1):) or some developers, if they don't need to use this variable in they code, they just use _
I am trying to nest 4 equilateral triangles of size 20, 40, 60 and 8 with an equal spacing of 7 within turtle.
Code:
from turtle import *
number_of_shapes = 4
side = 3
for spacing in range(1, number_of_shapes+1):
for sides in range(1, side+1):
forward(20*spacing)
left(360/side)
penup()
goto(-10*spacing, -7*spacing)
pendown()
I had to use -10*spacing in the goto(-10*spacing, -7*spacing) to get a near equal spacing between nested equilateral triangles. I was wondering if there was a way to just use the number 7 to achieve equal spacing.
Connect corners and you will see angel 30deg. It creates rectangular triangle with sides 10 and 7. Only 45deg creates rectangular triangle with with sides 10 and 10.
But values (10, 7) are not correct. Correct values are (10, 5.8) - but they may create spaces which don't look as good as for (10, 7) on monitors which use only integer values to display elements.
a = 10
b = 10 * tangens(30deg) = 5.8
I use these values to create space between triangels and next I draw line with angle 30 deg - it connects corners ideally. If you use b = 7 then you get your triangles and this line will not connect cornerts
from turtle import *
import math
number_of_shapes = 4
side = 3
a = 10
b = math.tan(math.radians(30)) * a
# b = 7
for spacing in range(1,number_of_shapes +1):
for sides in range(1,side+1):
forward(20*spacing)
left(360/side)
penup()
goto(-a * spacing, -b * spacing)
pendown()
left(30)
forward(100)
(10, 7) gives:
(10, 5.8) gives:
(10, 5.8) puts triangles in correct places but monitors are not ideal (they can only use integer values for x,y) so spaces between triangles may not looks as good as in your version.
This seems a classic "better living through stamping" problem. Triangles are drawn from one corner but stamped from the center, which solves the centering problem:
from turtle import Screen, Turtle
NUMBER_OF_SHAPES = 4
CURSOR_SIZE = 20
screen = Screen()
turtle = Turtle('triangle', visible=False)
turtle.fillcolor('white')
turtle.right(30) # lay bottom on horizontal
for sizing in range(NUMBER_OF_SHAPES, 0, -1):
turtle.shapesize(20 * sizing / CURSOR_SIZE)
turtle.stamp()
screen.exitonclick()
OP's drawn triangles on the left, the triangles stamped by the above code on the right:
If OP read his assignment question properly, only the bottom side of the triangles need to have a spacing of 7 :)
I need help turning polygon shapes (triangle and square) in Python turtle to match a picture.
Below I am trying to copy the image.
I specifically need help on what to add to my code given the triangle and square to have them repeat outwards like the picture. Because as of now the triangles and squares look like this (pentagon code is correct and works) All help is appreciated. Thank you.
import turtle
def polygon(turtle, side, length):
turtle.color("Blue")
for i in range(4):
turtle.backward(length)
turtle.left(side)
def polygon1(turtle, side1, length):
turtle.color("Green")
for i in range(3):
turtle.left(side1)
turtle.forward(length)
def polygon2(turtle, side2, length):
turtle.color("Red")
for i in range(5):
turtle.forward(length)
turtle.left(side2)
def main():
my_turtle = turtle.Turtle()
wn = turtle.Screen()
Bill = turtle.Turtle()
length = 100
side = 90
side1 = 120
side2 = 72
Bill.pensize(5)
Bill.speed(0)
#Pentagons
Bill.pu()
Bill.right(180)
y = -45
for i in range(5):
Bill.pu()
Bill.goto(60, y)
Bill.pd()
polygon2(Bill, side2, length)
y -= 20
#Triangle
Bill.pu()
Bill.left(240)
x = 45
for j in range(5):
Bill.pu()
Bill.goto(10, x)
Bill.pd()
polygon1(Bill, side1, length)
x += 20
#Square
Bill.pu()
Bill.left(240)
b = 6
for b in range(5):
Bill.pu()
Bill.goto(148, b)
Bill.pd()
polygon(Bill, side, length)
b -= 20
wn.exitonclick()
if __name__ == '__main__':
main()
pentagon code is correct and works
I don't believe the pentagon code is correct nor that you're approaching this in the correct way. The inner three shapes should form an equilateral triangle -- yours don't as you're eyeballing instead of calculating. Instead of trying to get the turtle to be in the right spot, why not have the turtle move forward in the direction of the sides of this central triangle, drawing polygons as it goes.
That is, embrace the drawing as a whole rather than trying to divide and conquer.
We'd need to make sure the polygon drawing code restores the turtle's state when it's done, so it can simply move forward to the next polygon. We'll need to make explicit which numbers are arbitrary, and which are calculable. Although the original diagram appears to use at least three turtles to achieve it's result, we'll do it with one as you attempted:
from turtle import Turtle, Screen
SHAPES = [(5, "Red"), (3, "Green"), (4, "Blue")]
LENGTH = 100
DELTA = 20
REPLICATIONS = 5
THICKNESS = 5
HEIGHT = (3 ** 0.5 / 2) * LENGTH # assumes 3 shapes, should fix!
DIVISIONS = 360 / len(SHAPES)
def polygon(turtle, sides, color):
turtle.color(color)
turtle.left(90)
turtle.forward(LENGTH / 2)
for _ in range(sides):
turtle.right(360 / sides)
turtle.forward(LENGTH)
turtle.backward(LENGTH / 2) # restore turtle to original state
turtle.right(90)
wn = Screen()
bill = Turtle()
bill.speed('fastest')
bill.pensize(THICKNESS)
bill.penup()
for offset, (sides, color) in enumerate(SHAPES):
bill.setheading(-DIVISIONS * offset - 90)
bill.forward(HEIGHT / 3) # assumes 3 shapes, should fix!
for _ in range(REPLICATIONS):
bill.pendown()
polygon(bill, sides, color)
bill.penup()
bill.forward(DELTA)
bill.home()
wn.exitonclick()
I am trying to fill the color in these squares:
Right now the turtle only fills the corners of theses squares, not the entire square.
Here is my code:
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.up
x = 0
y = 0
turtle.setpos(x,y)
numshapes = 8
for x in range(numshapes):
turtle.color(random.random(),random.random(), random.random())
x += 5
y += 5
turtle.forward(x)
turtle.left(y)
for i in range(squares):
turtle.begin_fill()
turtle.down()
turtle.forward(40)
turtle.left(angle)
turtle.forward(40)
print (turtle.pos())
turtle.up()
turtle.end_fill()
time.sleep(11)
turtle.bye()
I've tried moving around turtle.begin_fill() and end_fill() in numerous locations with no luckā¦ Using Python 3.2.3, thanks.
I haven't really used turtle, but it looks like this may be what you want to do. Correct me if I've assumed the wrong functionality for these calls:
turtle.begin_fill() # Begin the fill process.
turtle.down() # "Pen" down?
for i in range(squares): # For each edge of the shape
turtle.forward(40) # Move forward 40 units
turtle.left(angle) # Turn ready for the next edge
turtle.up() # Pen up
turtle.end_fill() # End fill.
You're drawing a series of triangles, using begin_fill() and end_fill() for each one. What you can probably do is move your calls to begin_fill() and end_fill() outside the inner loop, so you draw a full square and then ask for it to be filled.
Use fill
t.begin_fill()
t.color("red")
for x in range(4):
t.fd(100)
t.rt(90)
t.end_fill()
Along with moving begin_fill() and end_fill() outside the loop, as several folks have mentioned, you've other issues with your code. For example, this is a no-op:
turtle.up
I.e. it doesn't do anything. (Missing parentheses.) This test:
if num_str.isdigit():
Doesn't do much for you as there is no else clause to handle the error. (I.e. when it isn't a number, the next statement simply uses the string as a number and fails.) This calculation seems a bit too complicated:
angle = 180 - 180*(squares-2)/squares
And finally there should be a cleaner way to exit the program. Let's address all these issues:
from turtle import Screen, Turtle
from random import random
NUMBER_SHAPES = 8
print("This program draws shapes based on the number you enter in a uniform pattern.")
num_str = ""
while not num_str.isdigit():
num_str = input("Enter the side number of the shape you want to draw: ")
sides = int(num_str)
angle = 360 / sides
delta_distance = 0
delta_angle = 0
screen = Screen()
turtle = Turtle()
for x in range(NUMBER_SHAPES):
turtle.color(random(), random(), random())
turtle.penup()
delta_distance += 5
turtle.forward(delta_distance)
delta_angle += 5
turtle.left(delta_angle)
turtle.pendown()
turtle.begin_fill()
for _ in range(sides):
turtle.forward(40)
turtle.left(angle)
turtle.forward(40)
turtle.end_fill()
screen.exitonclick()