0

I have a function that draws a shape and records one of the positions of the points. Let's say that point is (2,1) so x = (2,1)

How do I use x in my main?

def shape():
    t.forward(10)
    x = t.position()

t.goto(x)

How can I make that work?

3
  • return x in shape() and change it to...t.goto(shape())? Commented Jun 7, 2012 at 1:07
  • I figured it out, add return x in shape(x) and in main x = shape(x) t.goto(x) Commented Jun 7, 2012 at 1:07
  • @user67784 what was your solution? Commented Jun 7, 2012 at 1:08

2 Answers 2

1

In order to access the value of x in the main program, return it from the function (via return x), in this case shape() that set/changes it.

Sign up to request clarification or add additional context in comments.

Comments

1

The code you have presented makes no sense in isolation (even apart from the scoping rules). You define a function which when called will create x. Then you want to use x. But you've never called the function, so x doesn't even exist! You may have called the function elsewhere, but you may have called it multiple times, in which case many versions of x may exist. Which one do you want?

That's the reason you can't simply refer to a variable defined in a function outside that function. It's not just a restriction to annoy you; it doesn't make sense as a concept.

The rule of thumb to follow is that you communicate information to a function by passing it in the function's arguments, and you communicate information back from a function to its caller by returning it. This means your function should probably look like this:

def shape(t):
    t.forward(10)
    return t.position

Then you would do:

x = shape(t)
t.goto(x)

You can access t as a non-local variable (global or outer function scope; it's not clear which you're using). But unless you have a good reason, it's usually better not to do that; explicitly passing information tends to make your code more readable, keep changes more isolated, and be more likely to be usable in more than one context (which is the point of making a function, after all). You can't access x without returning it (and if the only thing you do is return it, there's not much point in even giving it a name inside the function, since nobody else can use that name).

There are plenty of exceptions where using global variables (or other non-locals) are helpful, but life is generally easier when you regard them as exceptions to the general rule, so you're using those techniques deliberately when you do; your habit should be to avoid globals and non-locals.

1 Comment

I am using turtle graphics, t is the name of the object t = turtle.Turtle() sorry should have clarified on that

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.