0

I am experimenting with python, and I've made this little math game. Though I am having some issue with a scoring system. Each time the player gets an answer correct, I want the score to increment by 1. I have tried, however I haven't got it to increase each time the player gets something right. Heres the code

import operator
import random

operations = {
    "addition": ("+", operator.add),
    "substraction": ("-", operator.sub),
    "multiplication": ("*", operator.mul),
    "division": ("/", operator.floordiv),
}

def ask_operation(difficulty, maxtries=3):
    maxvalue = 5 * difficulty
    x = random.randint(1, maxvalue)
    y = random.randint(1, maxvalue)
    op_name, (op_symbol, op_fun) = random.choice(list(operations.items()))
    result = op_fun(x, y)
    score = 0

    print("Difficulty level %d" % difficulty)
    print("Now lets do a %s calculation and see how clever you are." % op_name)
    print("So what is %d %s %d?" % (x, op_symbol, y))

    for ntry in range(1, 1+maxtries):
        answer = int(input(">"))
        if answer == result:
            print("Correct!") 
            score += 1
            print score
            return True

        elif ntry == maxtries:
            print("That's %s incorrect answers.  The end." % maxtries)
        else:
            print("That's not right.  Try again.")
    return False

def play(difficulty):
    while ask_operation(difficulty):
        difficulty += 1
    print("Difficulty level achieved: %d" % difficulty)

play(1)
4
  • 4
    Is your indentation correct throughout the post? Commented Oct 23, 2013 at 19:24
  • No its not. I copied and pasted it from a textedit so I lost the formatting. I'll edit it Commented Oct 23, 2013 at 19:28
  • 3
    yeah fix the indentation please. At the moment, it looks like you set the score to 0 with every new question :/ Commented Oct 23, 2013 at 19:29
  • //Increment score// is not a comment in Python Commented Oct 23, 2013 at 19:30

1 Answer 1

2

The score is reset to 0 every time in ask_operation. You should initialize it in play instead.

By the way, //Increment score// is not valid Python. You can set comments in Python like this, even in Stack Overflow.

score += 1 # Increment score
Sign up to request clarification or add additional context in comments.

2 Comments

Ah yes, sorry I sometimes get my syntax mixed up. Thanks, how would I initialise it in the play function? Sorry, I am very new to python.
The same way you did in ask_operation. Make sure you keep it before the while loop so it only runs once.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.