I am trying to run following code in Python3.4, but I am getting error.
def checknumner():
i = 0
print("checknumber called...")
def is_even():
print("is_even called...")
global i
if i % 2 == 0:
print("Even: ", i)
else:
print("Odd: ", i)
i += 1
return is_even
c = checknumner()
print(c())
print(c())
print(c())
I am not able to access variable "i" in sub function.
When I comment out "global i" statment
D:\Study\Python>python generator_without_generator.py checknumber called... is_even called... Traceback (most recent call last): File "generator_without_generator.py", line 24, in <module>
print(c()) File "generator_without_generator.py", line 16, in is_even
if i % 2 == 0: UnboundLocalError: local variable 'i' referenced before assignment
When I add "global i" statment
D:\Study\Python>python generator_without_generator.py checknumber called... is_even called... Traceback (most recent call last): File "generator_without_generator.py", line 24, in <module>
print(c()) File "generator_without_generator.py", line 16, in is_even
if i % 2 == 0: NameError: name 'i' is not defined
Can anyone please explain this?