Variable is not defined in the function
<pre><code>import random

def game(n):
        while counter &lt; n:  
        n1 = random.randrange(1,10)
        n2 = random.randrange(1,10) 
        counter = 0     
        print (str(n1) + " + " + str(n1))
        answer = input("Enter answer: ")
if answer == n1+n2:
    print("Correct.")
else:
    print("Incorrect.")
    counter += 1
    pass
</code></pre>

<p>The error is in this line below telling that n1 is not defined.</p>

<pre><code>print (str(n1) + " + " + str(n1))
</code></pre>

<p>Here's what you need to fix:</p>

<ol>
<li>Your indentation is all over the place.</li>
<li>You were trying use <code>counter</code> as part of your condition in your loop before you even gave it a value.</li>
<li>Because you created <code>n1</code> and <code>n2</code> inside of the body of your while loop, after every guess <code>n1</code> and <code>n2</code> will be created again and assigned different values. I'm not sure if you wanted that to happen, but if you did you can simply move those 2 lines back inside the loop.</li>
<li>You weren't properly breaking out of your loop if the user guessed the correct answer. That's why I added <code>break</code>. That will end the loop upon a successful answer. Also, you don't need <code>pass</code> if the answer is incorrect. The loop will continue until it receives a correct answer or when it reaches the value of <code>counter</code>.</li>
</ol>

<p>Anyways, here is a fixed/working version of your code.</p>

<pre><code>import random

def game(n):
    counter = 0
    n1 = random.randrange(1,10)
    n2 = random.randrange(1,10) 
    while counter &lt; n:
        # move creation of n1, n2 here if you want #'s to change after every guess  
        print ('{} + {}'.format(n1, n2))
        answer = input("Enter answer: ")
        if answer == int(n1 + n2):
            print("Correct.")
            break
        else:
            print("Incorrect.")
            counter += 1
</code></pre>

<p>You should really read up on some basic Python topics, such as indentation, <code>while</code> loops, and variables.</p>

<p>Hope this helps!</p>

<p>Finally, here are 2 tests. One of which I successfully guess the correct answer and the other I guess until the counter is reached.</p>

<pre><code>4 + 9
Enter answer: 3
Incorrect.
4 + 9
Enter answer: 2
Incorrect.
4 + 9
Enter answer: 1
Incorrect.


9 + 8
Enter answer: 17
Correct.
</code></pre>

<p>In both of these examples I called the function with <code>game(3)</code>.</p>

python variables scope definition