[Tutor] scope problem?

Kristoffer Erlandsson krier115@student.liu.se
Tue May 13 20:04:03 2003


On Tue, May 13, 2003 at 04:53:25PM -0700, Peter Jakubowicz wrote:
> I'm probably doing something really dumb here, but I just wanted to test 
> this bit of code to generate a list of the prime numbers from 2 to n; but I 
> get an error message saying I haven't defined prime. But haven't I defined 
> it in line 2?
> 
> 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

prime is only defined in the local scope of the function sieve. Outside
this function, on the last line you posted, you try to print prime, but
this print statement is totally outside the function and can't see the
only-locally-defined prime. My guess is that you want to move the 'print
prime' statement into the function? Or maybe return the prime-list and
print it after calling the function, which I think is prettier.

Regards,
Kristoffer

-- 
Kristoffer Erlandsson
E-mail:  krier115@student.liu.se
ICQ#:    378225