Trying to include a counter on a student flashcard program

Joined
Jul 30, 2025
Messages
2
Reaction score
0
I did a student flashcard program and want to include a right/wrong counter for each student session. The program works except for the iteration counter. My last try is below, which returns a "local variable not associated with value" error. If I start the function with values def add_flashcards(right =0, wrong =0), it runs but doesn't give cumulative right/wrong when you do more iterations.

Any ideas how to make this work? Thanks!

Flashcards.jpg
 
Joined
Jul 4, 2023
Messages
607
Reaction score
81
Add global right, wrong at the start of your function so Python knows you're referring to the global variables.
Python:
from os import system
import random

system("cls")
right = 0
wrong = 0

def add_flashcards():
    global right, wrong  # <-- Fix here
    system('cls')

    card_one = random.randint(0, 10)
    card_two = random.randint(0, 10)
    correct = card_one + card_two
  
    ...

add_flashcards()

But you can pass and return values recursively (no global vars).
This version avoids global state and is better for scalability and testing.
A working version of the code online.
Python:
import random, os  # Import random for generating numbers, os for clearing the screen


# Function to clear the terminal screen (Windows or Unix-based systems)
def clear_screen():
    os.system("cls" if os.name == "nt" else "clear")


# Main function to handle flashcards logic
def add_flashcards(right=0, wrong=0):
    clear_screen()  # Clear screen at the beginning of each round
  
    # Generate two random numbers between 0 and 10
    card_one = random.randint(0, 10)
    card_two = random.randint(0, 10)
    correct = card_one + card_two  # Calculate the correct answer

    # Ask the user to solve the addition problem
    answer = input(f"{card_one} + {card_two} = ")

    # Check if the user's answer is correct
    if int(answer) == correct:
        print(f"Correct! You're right. This is {correct}")
        right += 1  # Increment correct counter
    else:
        print(f"Wrong! Addition should return a result {correct}")
        wrong += 1  # Increment incorrect counter

    # Display the current score
    score = f"\nRight: {right}. Wrong: {wrong}"
    print(score)

    # Ask if the user wants to continue
    play = input("Would you like another card? (yes|no|restart): ")

    if play.lower() in ["y", "yes"]:
        # Continue with current score
        add_flashcards(right, wrong)  # <-- Fix here
    elif play.lower() in ["r", "res", "restart"]:
        # Restart score from zero
        add_flashcards(right=0, wrong=0)
    else:
        # End game
        clear_screen()
        print(f"\nYour final score: {score}", "\nThanks for playing!")
        return


# Run the game only if this script is executed directly
if __name__ == "__main__":
    add_flashcards()
 
Last edited:
Joined
Jul 30, 2025
Messages
2
Reaction score
0
Thank you, VBService! small stuff to you, but big stuff for me. Learned about global variables, \n new line, and a better way to organize.

I will rewrite the full game (add, subtract, multiply, divide) using the recursive approach.

Much appreciated :)
 
Joined
Jul 7, 2024
Messages
4
Reaction score
0
You can also avoid both globals and recursion by wrapping the counters in a class. Each session then has its own right/wrong state:
Python:
import random, os


def clear_screen():
    os.system("cls" if os.name == "nt" else "clear")


class FlashcardGame:
    def __init__(self):
        self.right = 0
        self.wrong = 0


    def play_round(self):
        clear_screen()
        a, b = random.randint(0, 10), random.randint(0, 10)
        correct = a + b
        try:
            ans = int(input(f"{a} + {b} = "))
        except ValueError:
            return
        if ans == correct:
            self.right += 1
            print("Correct!")
        else:
            self.wrong += 1
            print(f"Wrong, it was {correct}")
        print(f"Right: {self.right} | Wrong: {self.wrong}")


    def run(self):
        while True:
            self.play_round()
            nxt = input("again? (yes|no|restart): ").lower()
            if nxt in ("restart", "r"):
                self.right = self.wrong = 0
            elif nxt not in ("yes", "y"):
                break


FlashcardGame().run()

This way counters are just attributes on the object — no global state and no recursive calls stacking up.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,342
Messages
2,571,405
Members
48,796
Latest member
katerack

Latest Threads

Top