0

Let us consider the following program

def fib(n): 
    result = []
    a, b = 0, 1
    while b < n:
        result.append(b)    
        a, b = b, a+b
        c = result
    print c
return result

f100 = fib(100)
print result
#print c

How can I access the variable 'c' from out side the function? Is it possible? I know

print result

will give the same, but i want to know is there any method to access 'c' outside the function?

justhalf
  • 8,960
  • 3
  • 47
  • 74
R S John
  • 507
  • 2
  • 9
  • 16
  • 3
    Why would you want to access `c`, when the value is already returned and stored in variable `f100`? And is the indentation for `return result` correct? And generally if you want to access something inside a function, you need to use either "global variable" or "return the value" – justhalf Nov 27 '13 at 09:46
  • 1
    that's imporssible, there is no `c` nor its value outside your function – alko Nov 27 '13 at 09:47
  • Maybe have a look at https://www.inkling.com/read/learning-python-mark-lutz-4th/chapter-17/python-scope-basics – dorvak Nov 27 '13 at 09:54

3 Answers3

1

You could declare c as global, although that's not generally a pattern you'd want to encourage. You'd do that like this:

c = None

def fib(n):
    global c

    result = []
    a, b = 0, 1
    while b < n:
        result.append(b)    
        a, b = b, a+b
        c = result
    return result

f100 = fib(100)
print result
print c

You could also restructure your function as a class with a __call__ method which would let you expose internal values as attributes, such as:

class fibber(object):
    def __init__(self):
        self.c = None

    def __call__(self, n):
        result = []
        a, b = 0, 1
        while b < n:
            result.append(b)    
            a, b = b, a+b
            self.c = result
        return result

fib = fibber()
f100 = fib(100)
print result
print fib.c
Benno
  • 5,640
  • 2
  • 26
  • 31
1

Local variables only exist in the context of the function they are defined in. That's what makes them local. So the whole variable c does not exist anymore once the function terminates and returns its result value.

You can of course save the value of that variable in a different one, e. g. a field of the function itself:

fib.c = c

Since the function itself will exist also after it terminated, so will its fields, and so will fib.c.

But I must stress that this is just a hack. Normally if you want to access a value outside of a function it is a good idea to make the variable holding that value not local.

Alfe
  • 56,346
  • 20
  • 107
  • 159
0

You can declare c a global variable:

def fib(n): 
    global c
    result = []
    a, b = 0, 1
    while b < n:
        result.append(b)    
        a, b = b, a+b
        c = result
    print c
    return result

result = fib(10)
print result
print c
Daniel
  • 695
  • 7
  • 20