MMelvin0581
MMelvin0581

Reputation: 503

I'm messing around with the turtle import in python 2.7 with loops and the turtle won't move

I'm messing around with the turtle import in python 2.7 with loops and I just see the screen flash and the program exits. Here is my code:

import turtle

colors = ["red", "orange", "yellow", "green", "blue", "purple"]
dColors = dict(enumerate(colors))


def circleOfShapes(aTurtle):
    edges = 3
    radius = 100
    for i in range(5):
        for k in range(360 / 5):
            aTurtle.color(dColors.get(i))
            aTurtle.circle(radius, None, edges)
            aTurtle.right(5)
        edges += 1
        radius -= 10


turt = turtle.Turtle()
turt.shape("arrow")

window = turtle.Screen()
window.bgcolor("white")
window.exitonclick()

circleOfShapes(turt)

This is just me trying to make something cool for my kid and get him interested in programming at an early age like I wish I would have. Thanks for the help.

Upvotes: 2

Views: 125

Answers (2)

user8874563
user8874563

Reputation:

For me the code runs fine. The only problem is in your for loop you are trying to loop with a float in line 11. You need to use an integer. You could int cast it. That should fix it. Hope this helps.

EDIT: Another problem with the code is the window.exitonclick()

Remove this or comment it out

Upvotes: 1

PM 2Ring
PM 2Ring

Reputation: 55469

Here's a slightly modified version of your code that runs on both Python 2 and Python 3.

import turtle

colors = ["red", "orange", "yellow", "green", "blue", "purple"]
dColors = dict(enumerate(colors))

def circleOfShapes(aTurtle):
    edges = 3
    radius = 100
    for i in range(5):
        for k in range(360 // 5):
            aTurtle.color(dColors.get(i))
            aTurtle.circle(radius, None, edges)
            aTurtle.right(5)
        edges += 1
        radius -= 10

turt = turtle.Turtle()
turt.shape("arrow")
#turt.hideturtle()
#turt.speed(0)

window = turtle.Screen()
window.bgcolor("white")

circleOfShapes(turt)
window.exitonclick()

You can speed things up by un-commenting either or both of #turt.hideturtle() #turt.speed(0)


I changed the division in your inner range call to 360 // 5 to ensure that it returns an integer. That makes the code more compatible with Python 2 and Python 3.

In Python 2 the / division operator will return an int if its operands are both ints, in Python 3 it will always return a float. So when you want an int quotient it's alwys best to use the // floor division operator.

The Python 2 range will accept a float arg, but it will give a deprecation warning. In Python 3 , it will just raise an error.

Upvotes: 0

Related Questions