Reputation: 61
I am trying to use count value inside a function and I am getting an error "local variable 'count' referenced before assignment" and I cannot use count=0 inside a function as it is recursive. I have also tried to keep global by defining count outside but it gives a syntax error. Please someone explain to me what is wrong and how to fix this code?
My code is as follows :
s=["abc","asd"]
d=""
count=0
def func():
if(count==len(s)):
exit(0)
else:
for i in s:
print(i[count])
count=count+1
func()
func()
Also Tried to keep global and I get Invalid syntax
s=["abc","asd"]
d=""
global count=0
def func():
if(count==len(s)):
exit(0)
else:
for i in s:
print(i[count])
count=count+1
func()
func()
Upvotes: 1
Views: 41
Reputation: 1203
You need to declare count as global inside the function like this:
s=["abc","asd"]
d=""
count=0
def func():
global count
if(count==len(s)):
exit(0)
else:
for i in s:
print(i[count])
count=count+1
func()
func()
Upvotes: 1