Search code examples
pythonvariablessyntax

Trying to draw Kenyan flag colours in python, encountered name error?


I thought trying to draw this thing in kenyan colours. Thought it would be simple and quick but ran into errors on the second line.

import turtle pen=turtle.Turtle() pen.speed('fastest')

When I take out the second line the error appears on the third line.

What am I doing wrong?

turtle.bgcolor('black')
col=('black','white','red','white','green')

That's what I'm trying to get to.


Solution

  • I've never used turtle myself, but after looking online I found this section of code which compiles:

    from turtle import *
    
    color('red', 'yellow')
    begin_fill()
    while True:
        forward(200)
        left(170)
        if abs(pos()) < 1:
            break
    end_fill()
    done()
    

    From that I think your issue is how you are importing. Try importing turtle the same way as above, and then do:

    color('black','white','red','white','green')
    

    instead of

    col=('black','white','red','white','green')
    

    ---Update-to-address-comments---

    Looking at your code, let me know if I misinterpreted where white space should be.

    from turtle import * 
    pen=turtle.Turtle() 
    pen.speed('fastest') 
    turtle.bgcolor('black') 
    color=('black','white','red','white','green')  
    for i in range(1,200,2):   
        t.pencolor(col[i%4])   
        for x in range(0,10):     
            t.circle(i)     
            t.rt(50)      
    turtle.done()
    

    Your issue isn't the import it's the use of t. instead of pen. New code should look like this:

    import turtle 
    pen=turtle.Turtle() 
    pen.speed('fastest') 
    turtle.bgcolor('black') 
    color=('black','white','red','white','green')  
    for i in range(1,200,1):   
        pen.pencolor(color[i%4])   
        for x in range(0,10):     
            pen.circle(i)     
            pen.rt(50)      
    turtle.done()
    

    The colors don't seem to work though. I'll look into it a bit more in a few minutes.

    note the for loop should iterate by 1 not 2 for the colors to switch properly.