简体   繁体   中英

how to pass variable from function using Python

I need to pass the seed inside the function to the main to do other things, but the seed will only show empty.

seed = {}
def search (seed):
    seed = 0
    print (seed)

search(seed)
print (seed)    

the 1st print (seed) >>>'0'

but the second print (seed) will only show >>>{}

I know 0 is a int, but even i change to string type like "hello" it will still have the same result. Please help

Return value from function and assign to a var.

seed = {}

def search (seed):
    abc = 123
    if abc == 123:
        seed = 0
        print (seed)
        return seed
    else:
        print ("why")

seed = search(seed)
print (seed)  
  1. You are declaring the seed variable as an empty list and inside the search method using it to assign integer values. This doesn't throw an exception as seed variable inside the search method is of local scope . But you may want to look into the usage of seed variable. Whether you need it to be a integer or a list . Not both.

  2. If you need the seed value in the main method, all you need to do is return the variable seed from the search method.

Like this:

def search (seed):
    abc = 123
    if abc == 123:
        # do something with *seed*
        return seed
    else:
        print ("why")

seed = search(seed)
print (seed)  

In your function, reassigning seed inside the scope of the function recreate a new var.

So you need to take seed from global vars.

Try this:

seed = {}

def search ():
    global seed
    abc = 123
    if abc == 123:
        seed = 0
        print (seed)
        return seed
    else:
        print ("why")

 seed = search(seed)
 print (seed)

By assigning seed in your function, you create a new local seed variable valid only within the function scope.

Check it ou - function id gives reference to variable:

In [95]: seed = {}

In [96]: id(seed)
Out[96]: 83506720

In [97]: foo(seed)
83506720
18955368

In [98]: id(seed)
Out[98]: 83506720

You may:

  • Return value and assign it outside function
  • Value of mutable variable may be changed by a function (assignment does not change value - it creates a new variable

    In [115]: def foo(seed, key, val): seed[key] = val .....:

    In [116]: seed = {}

    In [117]: foo(seed, 'value', 1)

    In [118]: seed Out[118]: {'value': 1}

  • You may use global qualifier (terrible)

seed={}
abc="seed"
seed[abc]={}

def getseed(seed):
    seed[abc]={0}

getseed(seed)
print (seed["seed"])

>>>'0'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM