[Tutor] Re: variable scope in nested functions: SOLUTION :-)
André Roberge
andre.roberge at gmail.com
Mon Apr 25 22:27:28 CEST 2005
Logesh Pillay wrote:
[snip]
>
> Consider a program I've just translated into python from my version in C.
>
> def erdos(n):
global found # added line
> found, r, s = False, 1, [0]*1000
> def choose (d, k):
global found # added line
> for i in -1, 1:
> s[d] = i
> if d < r:
> choose (d+1, k - i*d*d)
> elif k == i*d*d:
> found = True
> printout ()
> def printout ():
> print n, '=',
> for i in range (1, r+1):
> if s[i] == 1:
> print '+', i,'.',i,
> else:
> print '-',i,'.',i,
> print '\n'
> while not found:
> choose(1, n)
> r += 1
>
> The program is supposed to return to the python prompt as soon as it
> finds solution(s) at the smallest width r.
>
> I entered it exactly as it is expecting the same sort of error message
> for the boolean variable 'found'. There was none. Instead python
> simply fails to perform 'found = True' in choose() and it just keeps
> running (incidentally demonstrating the other part of this Erdos theorem
> that the no. can be so expressed in an infinite number of ways).
> Why the inconsistency in handling enclosing scope variables of type
> 'int' and 'bool'? Also, it can't be desirable that the interpreter
> effectively ignores a line of code without warning.
>
> Logesh
> _______________________________________________
Just add two global statements as written above and it will work just as
you would have expected it to!
André
More information about the Tutor
mailing list