I am trying to create a random triangle in python turtle with a for loop. I figured it out how to complete the task without a for loop, but I was instructed to use a for loop. I am going to add my code that isn’t working. I need explanations and examples if that is possible. I what to understand . range is (-r,r) and the starts at the origin. Thank you:
import turtle
import random turtle.penup() turtle.color('red')
def median(r):
L = [] for i in range (3):
L.append(randint(-r,r),randint(-r,r))
forward(r)
return L
turtle.pendown()
This textbox defaults to using Markdown to format your answer.
You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!
These answers are provided by our Community. If you find them useful, show some love by clicking the heart. If you run into issues leave a comment, or add your own answer to help others.
Sign up for Infrastructure as a Newsletter.
Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.
Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.
Heya,
Just an update on an the question,
It seems like you’re trying to create a function
median()
that generates three random points within a range (-r, r) and have the turtle draw lines between these points, thereby creating a random triangle.Your current approach has several issues. Here is a step-by-step fix for your function, along with explanations:
randint
from therandom
module. Also,turtle
needs to be imported as a standalone module, not as a function.randint()
function, which generates a random integer, directly insideL.append()
. However, you are missingrandom.
beforerandint()
. Moreover, you are trying to append two elements at once, which is not possible with.append()
. To append two values as a pair (representing coordinates), you should use a tuple.Instead of:
Use:
forward()
is a turtle method and you are trying to use it without reference to theturtle
object. It’s unclear what you’re trying to achieve with this function call in this context. Maybe you are trying to move the turtle forward by a distance ofr
. If that’s the case, it should beturtle.forward(r)
.Your function
median()
is defined to returnL
, which is a list of three random points. However, it’s unclear what you’re doing with this return value. If you want to draw a triangle using these points, you should include the drawing commands inside your function or in another part of your code.Here’s a corrected and completed version of your code that creates a random triangle using a
for
loop:This script generates three random points within a range (-r, r), moves the turtle to these points in order, and draws lines between them, creating a random triangle.