Author |
Message |
noelb6
|
Posted: 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? |
|
|
|
|
|
Sponsor Sponsor
|
|
|
Tony
|
Posted: 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. |
Tony's programming blog. DWITE - a programming contest. |
|
|
|
|
noelb6
|
Posted: 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 |
|
|
|
|
|
Tony
|
Posted: 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. |
Tony's programming blog. DWITE - a programming contest. |
|
|
|
|
noelb6
|
Posted: Tue Sep 20, 2011 8:50 pm Post subject: RE:Undefined variable |
|
|
That;s what the error said
But I defined i = 0 before |
|
|
|
|
|
Tony
|
|
|
|
|
noelb6
|
Posted: 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 |
|
|
|
|
|
noelb6
|
Posted: Tue Sep 20, 2011 9:15 pm Post subject: RE:Undefined variable |
|
|
main() |
|
|
|
|
|
Sponsor Sponsor
|
|
|
Tony
|
Posted: Tue Sep 20, 2011 9:17 pm Post subject: Re: RE:Undefined variable |
|
|
Python is indentation sensitive; they define blocks.
code: | 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 |
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. |
Tony's programming blog. DWITE - a programming contest. |
|
|
|
|
noelb6
|
Posted: Tue Sep 20, 2011 9:23 pm Post subject: RE:Undefined variable |
|
|
how do i fix that? |
|
|
|
|
|
Tony
|
|
|
|
|
noelb6
|
Posted: Wed Sep 21, 2011 10:54 am Post subject: RE:Undefined variable |
|
|
That worked, thank you.
Now time to fix my loops x.x |
|
|
|
|
|
|