I am newbee in Python . JUst wandering if it is possible to define a Global variable in Python.
I have this python code to compute total number of times Fib(2) has been accessed. But count is printing 0 when called.
import sys
def fib(n):
"""Takes input a natural number n > 0.
Returns n! """
global count
count = 0
if n == 1 or n == 0:
return 1
else:
if n == 2:
print 'encountered here::: '
count += 1
return fib(n-1) + fib(n-2)
def main():
x = int(raw_input('Enter a natural number > 0 :'))
print 'Fibonacci(%d) = %d' % (x, fib(x))
print 'Count =', count
if 1:
main()
global countinside thefibfunction.count = 0in module scope (after the import, for example). Be sure to keep theglobal countinfib.