I have this code and I tried to do a flowchart but I have no clue how to make one.
All of my Flowchart I made, don't make any sense.
Could anyone of you guys please help me out???
import turtle
STARTING_X, STARTING_Y = 350, 200
turtle.penup()
turtle.width(2)
turtle.setheading(180)
turtle.sety(STARTING_Y)
for a in range(1, 8):
turtle.penup()
turtle.setx(STARTING_X)
for b in range(a):
turtle.pendown()
turtle.circle(25)
turtle.penup()
turtle.forward(60)
turtle.sety(turtle.ycor() - 60)
turtle.done()
The code:
# part 1
import turtle
STARTING_X, STARTING_Y = 350, 200
turtle.penup()
turtle.width(2)
turtle.setheading(180)
turtle.sety(STARTING_Y)
# part 2
for a in range(1, 8):
turtle.penup()
turtle.setx(STARTING_X)
for b in range(a): # part 3
turtle.pendown()
turtle.circle(25)
turtle.penup()
turtle.forward(60)
turtle.sety(turtle.ycor() - 60)
turtle.done()
Part 1:
Importing turtle
Making global variables for starting positions
turtle stuff (read docs)
Part 2:
for loop that runs 8 times
turtle pen up (not drawing)
start at predefined x position
for loop (see Part 3)
lower the y position with 60
Part 3:
runs a times
turtle pendown (drawing)
drawing a circle
turtle penup (not drawing)
go forward with 60 (in this case, lower the x position with 60 because of the direction in part 1)
**Summary**
This program draws 8 lines of circles, and each nth line contains n circles aligned to the right like this:
*
**
***
****
*****
******
*******
********
But circles instead of stars
First of all thank you very much for your help :)
But my question now is how to put that information into a flowchart like this.
I mean what's the Condition 1 / 2, what are the statements etc.
Related
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 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()
def main():
square(0,0,50,'red')
def square(x,y,width,color):
turtle.penup()
turtle.goto(0,0)
turtle.fillcolor(color)
turtle.pendown()
turtle.begin_fill()
for number in range(5):
for count in range(4):
turtle.forward(width)
turtle.left(90)
turtle.end_fill()
x = x+50
turtle.goto(x,y)
turtle.showturtle()
Call the main function
main()
This gives me one row of 5 squares. How do i code an outer loop to draw 4 more
of rows of such 5 squares - a 5 by 5 checkerboard?
I simplified your "square" function to only draw a single square. Then I added a separate function which included a nested loop that calls the square function.
Trying to keep it simple and have only one responsibility for each function:
import turtle
def main():
board(5, 5, 50)
input("Hit enter to close")
def square(x,y,width,color):
turtle.penup()
turtle.fillcolor(color)
turtle.goto(x, y)
turtle.pendown()
turtle.begin_fill()
for side in range(4):
turtle.forward(width)
turtle.left(90)
turtle.end_fill()
def board(rows, columns, square_width):
turtle.showturtle()
for row in range(rows):
for column in range(columns):
color = "red" if (row + column)%2 == 1 else "white"
square(row*square_width, column*square_width, square_width, color)
turtle.hideturtle()
You already have code to draw a row of squares, that's the loop you have right now.
You want that code to be run 5 times, so just wrap it in another loop, making sure to modify variables as necessary. Something along the lines of this:
for i in range(5):
for number in range(5):
for count in range(4):
turtle.forward(width)
turtle.left(90)
turtle.end_fill()
x += width
turtle.goto(x,y)
x -= 5*width
y += width
Also a note on style, square() is ignoring most of its parameters. You hardcode your turtle to go to (0,0), regardless of the values of x and y. Because your later gotos use these values, your code will break if you set them to anything other than 0. Your line x = x+50 also ignores the value of width, even though the line the turtle draws uses it. Again, if you set it to anything other than 50, this will break.
I am a beginner at Python and I'm new to Stack Exchange. I'm trying to write a program that has 5 turtles moving within a square. I've got code that does what I want, but it's tedious and I'd like to initialize all my turtles using classes instead of doing it one by one. I just want them to start out at random coordinates and with a random heading.
The problems with my code:
Only one turtle is shown on screen. Two are defined in the code below.
The turtle's heading and coordinates aren't being initialized.
Here's the code that I've tried:
import numpy as np
from turtle import *
# setting up screen
reset()
screensize(550)
Screen().bgcolor('black')
tracer(0)
# drawing box
t0 = Turtle()
t0.penup()
t0.goto(-256,-256)
t0.color('cyan')
t0.pendown()
for i in range(4):
t0.forward(512)
t0.left(90)
t0.ht()
# parameters
velocity = 5
iterations = 200
boxsize = 512
ranheader = np.random.random()*360
ranx = np.random.random()*boxsize
rany = np.random.random()*boxsize
class turtle_agents(Turtle):
def _init_(self):
self.up()
self.seth(ranheader)
self.setpos(ranx,rany)
self.velocity = velocity
self.down()
# turtle
t1 = turtle_agents()
t1.color('green')
t2 = turtle_agents()
t2.color('blue')
# turtle movement
for turtle in turtles():
for i in range(iterations):
turtle.forward(velocity)
if turtle.xcor() >= 256:
turtle.goto(-256,t0.ycor())
elif turtle.xcor() <= -256:
turtle.goto(256,t0.ycor())
elif turtle.ycor() >= 256:
turtle.goto(t0.xcor(),-256)
elif turtle.ycor() <= -256:
turtle.goto(t0.xcor(),256)
update()
exitonclick()
only one turtle shown on screen. Two are defined in the code below.
the turtle's heading and coordinates aren't being initialized.
I believe the problem is that you defined the random position and heading once, outside the turtle creation loop so they all start in the same place, move in the same direction at the same speed. I.e. they're right on top of each other.
We don't need #BlivetWidget's explicit List to fix the problem since, as you discovered, turtles are already maintained in a list which we can get via the screen's turtles() method. Below is my rework of your code to fix various issues:
from turtle import Screen, Turtle
from random import randrange, randint
# parameters
COLORS = ['green', 'blue', 'red', 'orange', 'white']
ITERATIONS = 500
VELOCITY = 5
BOX_SIZE = 512
# setting up screen
screen = Screen()
screen.setup(BOX_SIZE + 50, BOX_SIZE + 50)
screen.bgcolor('black')
screen.tracer(False)
# drawing box
turtle = Turtle()
turtle.hideturtle()
turtle.color('cyan')
turtle.penup()
turtle.goto(-BOX_SIZE/2, -BOX_SIZE/2)
turtle.pendown()
for _ in range(4):
turtle.forward(BOX_SIZE)
turtle.left(90)
# turtle
for color in COLORS:
angle = randrange(360)
x = randint(-BOX_SIZE/2, BOX_SIZE/2)
y = randint(-BOX_SIZE/2, BOX_SIZE/2)
turtle = Turtle()
turtle.color(color)
turtle.setheading(angle)
turtle.penup()
turtle.setposition(x, y)
turtle.pendown()
# turtle movement
for _ in range(ITERATIONS):
for turtle in screen.turtles():
turtle.forward(VELOCITY)
x, y = turtle.position()
if x >= BOX_SIZE/2:
turtle.penup()
turtle.setx(-BOX_SIZE/2)
turtle.pendown()
elif x <= -BOX_SIZE/2:
turtle.penup()
turtle.setx(BOX_SIZE/2)
turtle.pendown()
elif y >= BOX_SIZE/2:
turtle.penup()
turtle.sety(-BOX_SIZE/2)
turtle.pendown()
elif y <= -BOX_SIZE/2:
turtle.penup()
turtle.sety(BOX_SIZE/2)
turtle.pendown()
screen.update()
screen.exitonclick()
I agree with #BlivetWidget that "you don't need to create a class just to move them to your starting positions". I use a simple loop above.
You should consider storing your turtles in a list, as the turtles are already objects and you don't need to create a class just to move them to your starting positions. Lists in Python are incredibly powerful because they can store arbitrary data types. Here, I will create 5 turtles and move them so you can tell them apart:
import turtle
num_turtles = 5
my_turtles = [turtle.Turtle() for i in range(num_turtles)]
for i, turt in enumerate(my_turtles):
turt.forward(50 * i)
You want to do the same thing, just replace my turt.forward() line with whatever you want the turtles to do. In your case, go to a random position within your square.
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()