Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to solve "object is not defined"

I wanted to randomize math question inside a snake game. And allow the snake to eat it.
Therefore I have to make question appear on the screen.
And the answer and wrong answer has to appear as the food.
How to solve ""answer" is not defined"?

class Question:

def question():
    num_1 = random.randint(1,12)
    num_2 = random.randint(1,12)
    
    n = random.randint(1,99)
    answer = num_1 * num_2
    canvas.create_text(window,0,
                     font=('consolas',50), text= "{}x{}=".format(num_1,num_2) , fill="red", tag="question")

The food code

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

class Food:

def __init__(self):

    x = random.randint(0, (GAME_WIDTH / SPACE_SIZE)-2) * SPACE_SIZE
    y = random.randint(0, (GAME_HEIGHT / SPACE_SIZE) - 2) * SPACE_SIZE

    self.coordinates = [x, y]

    canvas.create_text(x, y, 
                   font=('consolas',50), text= answer , fill="red", tag="food") # this is [line 47,Col52]

Problem : "answer"is not defined Pylance(reportUndefinedVariable) [Ln47,Col52]

>Solution :

Answer is not global. if you want to access it from the other class you either need to declare it as global variable or you need to pass the variable when calling the other class.

You might want to check here which explains global variables with playground for you to try

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading