[Tutor] scope problem?

Peter Jakubowicz beyondthezero@earthlink.net
Tue May 13 21:08:02 2003


OK, thanks, but now, testing it, I realize it doesn't do what I wanted it 
to do. I want it to work like the sieve of Eratosthenes: start with a list 
populated with the primes from 2 to n + 1, then leave 2 but take out all 
the multiples of 2, then leave 3 but take out all the multiples of 3, and 
so on. So if the user enters n, how would I populate the list.

This doesn't work:

def primeSieve(n):
     global prime[] = range(n)

Why doesn't this work? Thanks.

At 02:20 AM 5/14/2003 +0200, you wrote:
>On Tue, May 13, 2003 at 08:02:29PM -0400, David Broadwell wrote:
> > Peter Jakubowicz wrote:
> > > But haven't I defined it in line 2?
> > Yes inside sieve. But outside sieve prime is undefined unless you assign it
> > or return it.
> >
> > THIS:
> > prime = []
> > def sieve(n):
> >      prime = [2]
> >      for i in range(2, n + 1):
> >          for j in range(2, n + 1):
> >              if i % j == 0:
> >                  pass
> >              else:
> >                  prime.append(i)
> > print prime
>
>Actually, this won't work either. The prime that is used inside the
>function is a new, local, prime. You need to insert the line
>
>global prime
>
>first in the function for it to use the global one.
>
>Regards,
>Kristoffer
>
>--
>Kristoffer Erlandsson
>E-mail:  krier115@student.liu.se
>ICQ#:    378225
>
>_______________________________________________
>Tutor maillist  -  Tutor@python.org
>http://mail.python.org/mailman/listinfo/tutor