user2698178
user2698178

Reputation: 366

How to simultaneously access a global variable used inside while loop in another function?

I want to access the value of a variable which is being modified by the while loop, to be continuously printed outside loop. What I did:

x=0

def funcA():
    global x
    while True:
        x=x+1
        return x

def funB():
    print x

Now, I want x to keep print continously:

   1
   2
   3  and so on!

But it does not. I DONT WANT THIS:

def funB():
   while True:
       print x

That is to say that I dont want any while loop inside function funcB(). Thank you very much!

Upvotes: 1

Views: 2083

Answers (3)

reem
reem

Reputation: 7236

I don't know if this is what you are looking for, but you could use a generator.

def funcA():
    x = 0
    while True:
        yield x
        x += 1

def funcB():
    for x in funcA():
        print x #=> 1, 2, 3...

Upvotes: 2

tom10
tom10

Reputation: 69192

A callback would work and avoids the need for a global x:

def funcA(cb):
    x = 0
    while True:
        x=x+1
        cb(x)

def funB(a):
    print a    

funcA(funB)

Upvotes: 1

abarnert
abarnert

Reputation: 365717

You don't have a useful loop anywhere. In funcA, you have a while True:, but it just does a return every time through the loop, meaning it just runs once.

So, you could put a loop outside the two functions:

while True:
    funcA()
    funB()

Or, you could fix funcA so it loops forever instead of just once, then call funB from inside it:

def funcA():
    global x
    while True:
        x=x+1
        funB()

Or you could pass funB to funcA and have it call whatever it gets passed:

def funcA(*functions):
    global x
    while True:
        x=x+1
        for function in functions:
            functions()

funcA(funB)

Or you could make funcA yield each time through the loop instead of returning, and use that to drive funB:

def funcA():
    global x
    while True:
        x=x+1
        yield x

for _ in funcA():
    funB()

Or… there are all kinds of things you could do. The question is what you actually want to do. If you can explain that, someone can help you write it.


Meanwhile, you don't actually need a global variable in most of these cases. Given that funcA is already trying to return x, you can just pass the returned value in to funB in the outer-loop version, or pass x itself to funB and to function in the next two versions, and pass the yielded value in the generator version, …

Upvotes: 1

Related Questions