I understand you solved your issue, but random.choice() is better suited in your function:
def random_color():
L=['red','blue','green','yellow','black','pink','gold','violet','coral','lemon', 'chiffon','seagreen']
return random.choice(L)
Frage
I need a new random color for every new smaller square. Now it changes color only after while loop. Could you help me fix it?
def random_color():
colvar=random.randint(0,10)
L=['red','blue','green','yellow','black','pink','gold','violet','coral','lemon chiffon','sea green'] #wiki.tcl.tk/16166 website which I used to find names for colors
result=L[colvar]
return result
def square(color,x,y):
turtle.color(color)
turtle.begin_fill()
turtle.penup()
turtle.goto(x,y)
turtle.pendown()
line1=200 #creates a new smaller square
while line1>=10:
line1=line1-10
for i in range(2):
turtle.forward(line1)
turtle.right(90)
turtle.forward(line1)
turtle.right(90)
def drawsqr():
num=5
for i in range(num):
color=random_color() #change color after each complete cycle
x=250
y=250
square(color,x,y)
Lösung 2
I understand you solved your issue, but random.choice() is better suited in your function:
def random_color():
L=['red','blue','green','yellow','black','pink','gold','violet','coral','lemon', 'chiffon','seagreen']
return random.choice(L)
Andere Tipps
I understand you solved your issue, but random.choice() is better suited in your function:
I disagree. The problem with random.choice()
is you can get the same color on successive calls which is what you don't want:
>>> import random
>>> COLORS = ['red', 'blue', 'green', 'yellow', 'black', 'pink', 'gold', 'violet', 'orange', 'magenta', 'cyan']
>>> for _ in range(10):
... print(random.choice(COLORS))
...
green
pink
red
black
violet
orange
orange
violet
yellow
yellow
>>>
Using random.shuffle()
in combination with itertools.cycle()
gives you a randomized sequence of colors that repeats from which you can pluck unlike colors one after another:
import turtle
import random
import itertools
COLORS = ['red', 'blue', 'green', 'yellow', 'black', 'pink', 'gold', 'violet', 'orange', 'magenta', 'cyan']
def random_color(iterator=[]): # intentional dangerous default value
if not iterator: # empty container
colors = COLORS
random.shuffle(colors)
iterator.append(itertools.cycle(colors))
return next(iterator[0])
def square(length, x, y):
turtle.penup()
turtle.goto(x, y)
turtle.pendown()
while length >= 10:
color = random_color() # change color after each square
turtle.color(color)
turtle.begin_fill()
for _ in range(4):
turtle.forward(length)
turtle.right(90)
turtle.end_fill()
length -= 10
square(200, -100, 100)
turtle.done()
imputturtlegraphics,
setpcolor:("red,green,blue,gold,puple,maroon,claret,tuquoise etc")
,pendown
,goto("x$y$")
,movehundredstepsforward
,turnleft90
repeatprev2sX4