-1

I'm currently making a music quiz. I have come across a problem and don't know how to solve it. I'm using a variable called wrong. It is supposed to be an int, if I define it at the begin of the code it won't transfer into the function. And if define it in the function it resets.

K.Dᴀᴠɪs
  • 9,945
  • 11
  • 33
  • 43

2 Answers2

0

You can define the function without first creating the variable, or not, Python can handle either case.

def music(answers):
    # Where answers is [(user input, correct answer) ...]
    wrong = []
    for i in answers:
        if i[0] == i[1]:
            pass
        else:
          wrong.append(i)  
    return wrong

wrong = music(answers)

Or if you want to pick up where you left off with previous values for answers and wrong:

wrong = [(previous values, previous answers) ...]

def music(answers, wrong = []):
    # Where answers is [(user input, correct answer) ...]
    wrong = []
    for i in answers:
        if i[0] == i[1]:
            pass
        else:
          wrong.append(i)  
    return wrong

wrong = music(answers, wrong=wrong)
Charles Landau
  • 4,187
  • 1
  • 8
  • 24
0

Easy. Make it global. When you define wrong at the beginning like this

wrong = 10

Just call global inside the function and it should use the initialized variable

def your_function(): 
    global wrong
    wrong_temp = wrong
    #use wrong_temp however 

I would also take a look at this link. It looks like this might solve the question you are asking, but it is also helpful to understand how global variables work. Using global variables in a function