Python Forum

Full Version: User defined functions inside other user defined functions
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I want to make use of a function I have defined inside another function. But I can't figure out how.

I have defined a function in for the turtle-world, jump(x, y), that creates a turtle in the turtle-world, hides the turtle and then moves it to coordinates x and y with the following code
def jump(x, y):
    import turtle

    t = turtle.Turtle()
    t.hideturtle()
    t.penup()
    t.goto(x, y)
    t.pendown()
I have tried the function without hiding the turtle and it works fine.

I now want to use this function to define a new function, rectangle(x, y, width, height, color), that creates a rectangle with bottom left corner in (x, y), with given width and height and fillcolor. I have written this
def rectangle(x, y, width, height, color):
    jump(x, y)
    t.setheading(270)
    t.fillcolor(color)
    t.begin_fill()
    for i in range(4):
        t.left(90)
        if i % 2 == 0:
            t.forward(width)
        else:
            t.forward(height)
    t.end_fill()
When I try to use this function Idle returns "NameError: name 'jump' is not defined". It simply won't let me use the function jump inside the function rectangle. Is it not possible to use a user defined function inside another function? or how can I solve this?

I should add that the function rectangle works perfectly when I replace the line with "jump(x, y)" with the lines in jump(x, y) as:

def rectangle(x, y, width, height, color):
    import turtle

    t = turtle.Turtle()
    t.hideturtle()
    t.penup()
    t.goto(x, y)
    t.pendown()
    t.setheading(270)
    t.fillcolor(color)
    t.begin_fill()
    for i in range(4):
        t.left(90)
        if i % 2 == 0:
            t.forward(width)
        else:
            t.forward(height)
    t.end_fill()
If you post all of your code in one big block would we see that jump is defined above or below rectangle?

You say defined inside another function. I do not see that, but I do see you calling it from another function.

When you have an error you should post the entire error, there may be other clues in it.

Also, you only need to import turtle once, do so at the top of your module unless there's a reason not to.