Here's what you need to fix:
- Your indentation is all over the place.
- You were trying use
counter
as part of your condition in your loop before you even gave it a value.
- Because you created
n1
and n2
inside of the body of your while loop, after every guess n1
and n2
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.
- You weren't properly breaking out of your loop if the user guessed the correct answer. That's why I added
break
. That will end the loop upon a successful answer. Also, you don't need pass
if the answer is incorrect. The loop will continue until it receives a correct answer or when it reaches the value of counter
.
Anyways, here is a fixed/working version of your code.
import random
def game(n):
counter = 0
n1 = random.randrange(1,10)
n2 = random.randrange(1,10)
while counter < 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
You should really read up on some basic Python topics, such as indentation, while
loops, and variables.
Hope this helps!
Finally, here are 2 tests. One of which I successfully guess the correct answer and the other I guess until the counter is reached.
4 + 9
Enter answer: 3
Incorrect.
4 + 9
Enter answer: 2
Incorrect.
4 + 9
Enter answer: 1
Incorrect.
9 + 8
Enter answer: 17
Correct.
In both of these examples I called the function with game(3)
.