I am trying to create a Koch snowflake generator in Python using the Turtle library and recursion. I have a list of strings with hex codes in them and I am using the variable color
to have the pen change colors in the order of the list. As you can see, I defined color
outside of the function definition but when I try to run it, I get and UnboundLocalError saying that color
was referenced before it was assigned. How can I fix the error so my code will run as intended?
Here is some of the code I wrote to generate the Snowflake. color
is supposed to increase by one every time a line is drawn, so then the next time a line is drawn the color used is a palette[color % 6]
import turtle
turtle.colormode(255)
palette = ["#ff0f7b","#fd445d","#fc5552","#fa8139","#f98a34","#f89b29"]
color = 0
# Draw a Koch curve
def koch(iteration, length):
if iteration == 1:
turtle.forward(length/3)
turtle.pencolor(palette[color % 6])
color = 1
else:
koch(iteration-1, length/3)
turtle.left(60)
here is the error message I am getting:
Traceback (most recent call last):
File "C:\Users\hummi\Python Files\koch_snowflake.py", line 49, in <module>
koch_snowflake(4, 480)
File "C:\Users\hummi\Python Files\koch_snowflake.py", line 41, in koch_snowflake
koch(iteration, length)
File "C:\Users\hummi\Python Files\koch_snowflake.py", line 15, in koch
koch(iteration-1, length/3)
File "C:\Users\hummi\Python Files\koch_snowflake.py", line 15, in koch
koch(iteration-1, length/3)
File "C:\Users\hummi\Python Files\koch_snowflake.py", line 15, in koch
koch(iteration-1, length/3)
File "C:\Users\hummi\Python Files\koch_snowflake.py", line 12, in koch
turtle.pencolor(palette[color % 6])
UnboundLocalError: local variable 'color' referenced before assignment
CodePudding user response:
You just need to add a global color
statement, like this:
color = 0
# Draw a Koch curve
def koch(iteration, length):
global color
if iteration == 1:
turtle.forward(length/3)
turtle.pencolor(palette[color % 6])
color = 1
Without that addition, modifying the value of color
makes it a locally scoped variable. Since in that local scope, it hasn't been assigned to yet, and the increment statement requires a previous value for the variable, you get the error that you are seeing. Adding the global color
statement forces the statement to refer to the global color
value, even though it is modifying the value. If you were only reading from color
, the global color
statement wouldn't be necessary. A slightly strange Python factoid here.