1

If a defined a function like this:

def plop(plop):
    ploplop = 1234
    if plop == ploplop:
         print "I plopped"

How do I take ploplop outside of the scope of the function?

4 Answers 4

9

You return it, and capture it on the other side.

def plop(plop):
    ploplop = 1234
    if plop == ploplop:
         print "I plopped"
    return plopplop

someval = plop(1235)
Sign up to request clarification or add additional context in comments.

2 Comments

I tried a variation of that on the code I'm practicing with and that wasn't quite the result I expected. I wanted to take a variable called big that was declared in a function and use it with another function.
Okay. But you still have to do it this way, or incur a major rewrite of the code.
2
def plop(plop):
    global ploplop 
    ploplop = 1234
    if plop == ploplop:
         print "I plopped"

but global variables should almost never be used

Comments

1

another solution is to add an attribute to the function. (I changed the function name because there are too many plops):

def f(plop):
    f.ploplop = 1234
    if plop == f.ploplop:
         print "I plopped"
f(5)
print f.plopplop

Comments

0

You're not giving enough information for a good answer. What's the relationship between the two functions and the variable?

If the variable represents some sort of persistent state that the two functions operate on, then you want to create a class with two methods and a member variable:

class Plopper( object ):
    ploplop = 1234

    def plop( self, ploppity ):
        if ploppity == self.ploplop:
            print "I plopped"   # ew.

    def plop2( self, ploppity ):
        if ploppity == self.ploplop * 2:
            print "I plopped twice"

a = Plopper()

a.plop( 1234 )
a.plop2( 2468 )

If the variable controls the behavior of the functions and you just need to be sure they're consistent, pull the variable out of the method to a global (note that, contra user1320237, you don't need to declare it global if you're only reading its value):

PLOPLOP = 1234    # I like the all-caps convention for global constants

def plop(plop):
    if plop == PLOPLOP:
         print "I plopped" 

def plop2(plop):
    if plop == 2 * PLOPLOP:
         print "I plopped twice" 

plop(1234)
plop2(2468)

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.