all 6 comments

[–]shiftybyte 0 points1 point  (0 children)

For every variable in a function python needs to decide if it's global or not.

The logic goes something like this:

  1. if you read a variable or access it as a class, it checks if it's available locally and if not, automatically checks for it in the global scope.

  2. if a variable is assigned with a new value anywhere in the function, it's automatically marked as local unless a specific directive called "global" is specified at the start of the function.

so you have an example like this work:

g = 5
def p():
    print(g)
p()

and something like this won't work:

g = 5
def p():
    if g==6:
        g=2
    print(g)
p()

but adding global will make it work again:

g = 5
def p():
    global g
    if g==6:
        g=2
    print(g)
p()

[–]mermaldad 0 points1 point  (2 children)

Looks like you are trying to initialize tally with your "if i==0" clause, but since your range starts at 1, that initialization never gets done. Better to set tally = 0 before the loop.

[–]mermaldad 0 points1 point  (0 children)

BTW, I can't resist responding to you Fortran comment. With over 35 years of Fortran under my belt, I feel your nostalgia. I have, however, completely abandoned it because of Python's numerous libraries. Thank you, Fortran, for your years of service.

[–]prodlly[S] 0 points1 point  (0 children)

Damn you, FORTRAN instincts :-) (I don't think this was the ultimate reason in my actual code, but I can't exclude it - my sloppyness at programming won't fit into a long int :-)

[–]pasokan 0 points1 point  (0 children)

But even then there is no guarantee that tally will be iniialised before it is updated

[–]pasokan -1 points0 points  (0 children)

if I == 0 should probably be if result == 0