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.
Asked
Active
Viewed 40 times
-1
-
1pass the variable as function parameter and return it at the end of the function – Florian H Dec 05 '18 at 14:50
-
1Could you post your code? – toti08 Dec 05 '18 at 14:50
-
3Welcome to SO! Please remember to include a [MCVE](https://stackoverflow.com/help/mcve) – Charles Landau Dec 05 '18 at 14:50
2 Answers
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

youngdeveloper
- 13
- 4
-
-
1Word, bro. always got to remember good coding practices @CharlesLandau – youngdeveloper Dec 05 '18 at 16:37