Accessing variable from a function within a function

Michael Hoffman cam.ac.uk at mh391.invalid
Sun Jun 24 14:18:00 EDT 2007


Nathan Harmston wrote:
> Hi,
> 
> I m playing around with extended euclids algorithm from Knuth. I m
> trying to build a function with a function inside it.
> 
> def exteuclid(m,n):
>  a,a1,b,b1,c,d = 0,1,1,0,m,n
>  def euclid(c,d):
>        q = c /d
>        r = c % d
>        if r == 0:
>            print a,b
>            return d
>        else:
>            print a1,a,b1,b,c,d,q,r
>            t = b1
>            b = t - q * b
>            a = t - q * a
>            c,d,a1,b1 = d,r,a,b
>            return euclid(c,d)
>    return euclid(c,d)
> 
> Unfortunately this doesnt work since a,a1,b,b1 arent declared in the
> function. Is there a way to make these variables accessible to the
> euclid function. Or is there a better way to design this function?

Well, it would be simpler to pass through all the variables rather than 
relying on variables in a wider scope.
-- 
Michael Hoffman



More information about the Python-list mailing list