Computer Science Canada Undefined variable |
Author: | noelb6 [ Tue Sep 20, 2011 8:17 pm ] |
Post subject: | Undefined variable |
So I just started python today for a class, and I defined my variables. But when I run the program it says that the variable isn't defined. How can I fix this? |
Author: | Tony [ Tue Sep 20, 2011 8:36 pm ] |
Post subject: | RE:Undefined variable |
Likely a scope issue. A variable with the same name might be defined elsewhere, but it's not visible from where you are trying to use it. E.g. code inside one function doesn't see local variables defined in another function. |
Author: | noelb6 [ Tue Sep 20, 2011 8:40 pm ] |
Post subject: | RE:Undefined variable |
it says "line 15, in <module> while i == 0: NameError: name 'i' is not defined" But i have it define before that and i tried erasing it and it still didnt work |
Author: | Tony [ Tue Sep 20, 2011 8:44 pm ] |
Post subject: | RE:Undefined variable |
in the little amount of code that you've shared, I don't see you defining that variable. |
Author: | noelb6 [ Tue Sep 20, 2011 8:50 pm ] |
Post subject: | RE:Undefined variable |
That;s what the error said But I defined i = 0 before |
Author: | Tony [ Tue Sep 20, 2011 9:03 pm ] |
Post subject: | RE:Undefined variable |
post the code. |
Author: | noelb6 [ Tue Sep 20, 2011 9:13 pm ] |
Post subject: | RE:Undefined variable |
def main(): print("This program prints out the 978th prime number") x = 1 p = 0 z = 1 i = 0 while p < 978: while i == 0: if x % z == 0: i = 1 if z == x/2: i = 2 else: i = 0 z = z + 1 if i == 1: print x, "is a composite" else: print x, "is a prime" p = p + 1 |
Author: | noelb6 [ Tue Sep 20, 2011 9:15 pm ] |
Post subject: | RE:Undefined variable |
main() |
Author: | Tony [ Tue Sep 20, 2011 9:17 pm ] | ||
Post subject: | Re: RE:Undefined variable | ||
Python is indentation sensitive; they define blocks.
i is defined and is local to main(). your while loops are outside of main. code inside while loops can't see what's defined inside of main. |
Author: | noelb6 [ Tue Sep 20, 2011 9:23 pm ] |
Post subject: | RE:Undefined variable |
how do i fix that? |
Author: | Tony [ Tue Sep 20, 2011 9:27 pm ] |
Post subject: | RE:Undefined variable |
Have them all in the same scope http://en.wikipedia.org/wiki/Scope_(computer_science) The easiest way would be to simply place your while loops inside of main(). |
Author: | noelb6 [ Wed Sep 21, 2011 10:54 am ] |
Post subject: | RE:Undefined variable |
That worked, thank you. Now time to fix my loops x.x |