[Tutor] calling function

Alan Gauld alan.gauld at yahoo.co.uk
Mon Nov 27 19:19:50 EST 2017


On 27/11/17 20:47, Howard Lawrence wrote:
> import turtle
> # this part draws a square
> def square():
> 
>     my_turtle = turtle.Turtle()

Note that this creates my_turtle as a local
variable inside the function. It will not
be visible outside the function.

>     my_turtle.forward(100)
>     my_turtle.left(90)
>     my_turtle.forward(100)
>     my_turtle.left(90)
>     my_turtle.forward(100)
>     my_turtle.left(90)
>     my_turtle.forward(100)
> square()
> 
> my_turtle.forward(100)

So this should fail; with an error message
 - a name error most likely.

> # this is a second square
> square()

And this creates a new square directly on top of
the earlier one, so they look like one.

You need to create the turtle outside the function
and then refer to it from inside the function,
ideally by passing it in as an argument:


def square(aTurtle):
    aTurtle.forward(100)
etc...

my_turtle = turtle.Turtle()
square(my_turtle)
my_turtle.forward(100)
square(my_turtle)

HTH
-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list