Marzena writes:
I'm writing to you because neither me nor my 11-year old daughter with whom we're learning Python can figure out where the problem is. We get the following error:
================ RESTART: C:/Users/Enarpol/Desktop/brajan.py ================
Traceback (most recent call last):
File "C:/Users/Enarpol/Desktop/brajan.py", line 5, in <module>
class Piłka:
File "C:/Users/Enarpol/Desktop/brajan.py", line 20, in Piłka
if pozycja[1] <= 0:
NameError: name 'pozycja' is not defined
And the code is exactly like in the book (some words are in Polish, but I assume it's not a problem for you to trace the error despite of it)
Your problem problem is caused by indentation and the idea of "scope" - I guess you're using the Polish language version of the book, so I'm not sure of the correct page number, but in the English language version of the book the section on Variables and Scope (page 84) would be useful to re-read.
In short, here is the incorrect bit of your code:
def rysuj(self):
self.płótno.move(self.id, self.x, self.y)
pozycja = self.płótno.coords(self.id)
if pozycja[1] <= 0:
self.y = 3
If I re-indent this with visible spaces, to show how it should look, hopefully you can see what you need to fix in the rest of your code:
def rysuj(self):
self.płótno.move(self.id, self.x, self.y)
pozycja = self.płótno.coords(self.id)
␣␣␣␣if pozycja[1] <= 0:
␣␣␣␣ self.y = 3
Why does this make a difference? Because in the case of rysuj
above, the variable pozycja
is only visible within the function - or to be exact, within the block of code that makes up the function. And how do we create a block of code? Basically through indentation. Your if
statement was at the same indentation level as def rysuj(self)
, so it wasn't part of the function and that's why you're getting the error name 'pozycja' is not defined
.
Hope that helps.