Search code examples
pythonvariablescalculatormicropython

X is not defined but x has been defined


I am writing a program for the ti-84 using python. It is designed to get a differential equation from the user, process it, and draw a slope point field for that equation. The part that is giving me issues is the eval function (I know, security risk) when i evaluate the equation it gives me an error, 'name 'x' is not defined'. This error only occurs when running the program on the calculator, it does not occur when I run that section of code on my computer. The problem is that 'x' has already been defined above. Why is this happening?

import ti_pltlib as plt
class Field:

   self.equation = 2*x+2*y

   for pos_x in range(plt.xmin, plt.xmax):
       for pos_y in range(plt.ymin, plt.ymax):
           x = pos_x-0.25
           y = pos_y-0.25
           x0 = eval(self.equation) #Error occurs right here
           x += 0.5
           x1 = eval(self.equation)
           y0 = eval(self.equation)
           y += 0.5
           y1 = eval(self.equation)

The error in more detail is:

 'File "<stdin>", line 1, in <module>
 File "FEILD.py", line 45, in <module>
 File "FEILD.py", line 45, in <module>
 File "<string>", line 1, in <module>
 NameError: name 'x' is not defined'

Solution

  • Remember that the TI-84 runs micropython (well, circuitpython), and MicroPython is not Python. You need to be aware of the differences when writing code in both languages. In this case, you are hitting the fact that eval() in micropython does not have access to local variables:

    MicroPython doesn’t maintain symbolic local environment, it is optimized to an array of slots. Thus, local variables can’t be accessed by a name. Effectively, eval(expr) in MicroPython is equivalent to eval(expr, globals(), globals()).

    That entire document is good reading; it talks about a number of differences between CPython (aka "regular Python") and MicroPython.