Skip to content Skip to sidebar Skip to footer

How To Share Values Between Functions In Python?

I have the following 2 functions: a = 20 b = 45 def function1(): coin = np.random.randint(0, 100) a2= a+coin return a2 def function2(): b2= b+coin return b

Solution 1:

After Edit

While you can use a global variable, I would recommend using a class:

class Functions:

    def __init__(self, a, b):
        self.a = a
        self.b = b
        self.coin = 0

    def function1(self):
        self.coin = np.random.randint(0, 100)
        a2 = self.a + self.coin
        return a2

    def function2(self):
        b2 = self.b + self.coin
        return b2

f = Functions(a=20, b=45)
f.function1()
f.function2()

Both functions are tightly coupled. Therefore, a class seems more appropriate to hold them. Ideally, functions should be independent. On the other hand, methods of a class are expected to depend on each other.

Old Answer

I recommend using arguments for your functions. This makes them independent:

def function1(a):
    coin = np.random.randint(0, 100)
    a2 = a+coin
    return a2, coin

def function2(coin):
    b2 = b+coin
    return  b2

a = 20
b = 45

a2, coin = function1(a)
print(function2(coin))

This line:

return a2, coin

"returns two results". Actually, it builds an intermediate tuple. And this line:

a2, coin = function1(a)

unpacks this tuple into to variables again.


Solution 2:

"Easiest" way would be to make coin a global variable. I think that may be the solution that requires fewer changes to the code as well:

a = 20
b = 45
coin = 0       # good practice to always initialize vars

def function1():
    global coin         # will create and use "coin" from the global scope
    coin = np.random.randint(0, 100)
    return a+coin

def function2():
    b2 = b+coin
    return  b2

function1()

function2()

Solution 3:

Ok with only one result in function1(), and without a Class maybe you can retro-find coin?

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from random import randrange

a = 20
b = 45

def function1():
    coin = randrange(0, 100)
    a2 = a + coin
    return a2


def function2(coin):
    b2 = b + coin
    return b2

coin = function1() - a

f2 = function2(coin)

print("coin: {}".format(coin))
print("f2: {}".format(f2))

Post a Comment for "How To Share Values Between Functions In Python?"