4

A really simple question, and I'm sure I knew it but must have forgotten

When running this code:

x = 0
def run_5():
    print "5 minutes later"
    x += 5
    print x, "minutes since start"

run_5()
print x

I get x isn't defined. How can I have x used in the function and effected outside of it?

3
  • 1
    Why aren't you using the return statement? Please update the question to explain what you expected to happen without any return statement. Commented Oct 11, 2010 at 11:07
  • It wasn't what I expected. I just didn't know how to correctly use it. Commented Oct 11, 2010 at 11:13
  • Please update the question to explain what you expected. Commented Oct 11, 2010 at 12:34

4 Answers 4

10

Just return a value ?

x = 0
def run_5():
    print "5 minutes later"
    x += 5
    return x

x=run_5()
print x
Sign up to request clarification or add additional context in comments.

Comments

10

Put global x at the start of the function.

However, you should consider if you really need this - it would be better to return the value from the function.

1 Comment

Hush! We don't want people to know about global before they know about return. In a perfect world, they'd even understand how bad globals are before they learn about global.
1

Just to make sure, the x that is not defined is the one on line 4, not the one on the last line.

The x outside the function is still there and unaffected. It's the one inside that can't have anything added to it because, as far as Python is concerned, it does not exist when you try to apply the += operator to it.

Comments

-1

I think you need to define a variable outside the function, if you want to assign it a return value from the function.

The name of the variable can be different than the name in function as it is just holding it

Comments

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.