0

I am trying to run the below script:

i = 0
numbers = []

def number_includer(max_num):        

    while i < max_num:
        print "At the top i is %d" % i
        numbers.append(i)

        i = i + 1
        print "Numbers now: ", numbers
        print "At the bottom i is %d" % i

number_includer(7)


print "The numbers: "    

for num in numbers:
    print num

but when i simply do:

numbers = []

def number_includer(max_num):
    # Used i equals 0 inside the function here.
    i = 0

    while i < max_num:
        print "At the top i is %d" % i
        numbers.append(i)

        i = i + 1
        print "Numbers now: ", numbers
        print "At the bottom i is %d" % i

number_includer(7)


print "The numbers: "    

for num in numbers:
    print num

i don't want answer but an explanation, if the problem is with using a local variable inside def which is predefined on the outside, its got no problem with the list 'numbers' being global?

hungryWolf
  • 391
  • 1
  • 3
  • 15
  • Add `global i` to the top of `number_includer`. If you only read a variable from a function, it will look up-level for it if needed, but if you write a variable in a function, it creates a new local variable for it unless it is declared `global` (or also `nonlocal` in Python 3). – Tom Karzes Feb 03 '16 at 08:23
  • global? isn't using global unorthodox in python? – hungryWolf Feb 17 '16 at 10:03
  • I was explaining how to make it do what you intended. You were clearly trying to access the global copy of `i`. I told you how. I never said it was good practice. – Tom Karzes Feb 17 '16 at 10:13
  • sorry about what i said, thank you for answering. – hungryWolf Feb 21 '16 at 09:08

0 Answers0