I'm currently doing the logic testing of my assignment so my code still needs some refactoring and removing of none needed globals and imports but I'm getting a randomly occurring error.
The error will occur randomly, sometimes it might not happen for 40 iterations, other times it will happen on the first one. It's completely random.
the error occurs on the line where i calculate the answer to the sum beforehand and store it.
answer = operator(times, toTimesBy)
I get an error saying the variable operator is referenced before assignment although this error only pops up randomly.
UnboundLocalError: local variable 'operator' referenced before assignment
#import required additional libraries
import random
import operator
import sys
global times
global toTimesBy
global answer
global ops
global stringOperator
global questionCounter
#dictionary to hold operators which allow assignment to variables
ops = {"+": operator.add,
       "-": operator.sub,
       "*": operator.mul}
questionCounter = 1
print(questionCounter)
def generate(questionCounter):
    #set question counter
    questionCounter = questionCounter + 1
    #generate questions
    times = random.randint(1, 12)
    toTimesBy = random.randint(1, 12)
    #randomly select the operator
    operatorSelector = random.randint(1, 100)
    if operatorSelector in range(0, 32):
        operator = ops["+"]
        stringOperator = "+"
    elif operatorSelector in range (33, 65):
        operator = ops["-"]
        stringOperator = "-"
    elif operatorSelector in range(66, 100):
        operator = ops["*"]
        stringOperator = "*"
    #to work out answer
    answer = operator(times, toTimesBy)
    print(answer)
    #print which question the user is answering
    print('question ' + str(questionCounter) + ' is:')
    #print the question
    print(str(times) + stringOperator + str(toTimesBy))
    #collect input
    userInput = input('What is your answer? ')
    #check if right
    if userInput == str(answer):
        print('correct')
        generate(questionCounter)
        #check if wrong
    else:
        print('wrong')
        generate(questionCounter)
generate(questionCounter)
 
     
     
    