0

I gave this following program in Python just to understand scopes of variables, but I'm getting the error:

count = 0
def hello_func():
    if(count == 5):
        return 0
    print("Hello")
    count+=1
    hello_func()

hello_func()  

Error :

 UnboundLocalError: local variable 'count' referenced before assignment 

Can you explain what I'm doing wrong? And how do I declare count has global variable without altering the structure of the above program?

1 Answers1

0

When using global variables within a function, you need to declare it explicitly:

count = 0
def hello_func():
    global count
    if(count == 5):
        return 0
    print("Hello")
    count+=1
    hello_func()

hello_func()  

The global count in the third line declares I am using the global variable.

Dinari
  • 2,487
  • 13
  • 28