Local (?) variable referenced before assignment
Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Mysterious Puzzle
--
Chapters
00:00 Question
00:38 Accepted answer (Score 281)
01:17 Answer 2 (Score 64)
01:32 Answer 3 (Score 12)
01:46 Thank you
--
Full question
https://stackoverflow.com/questions/1190...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #python3x
#avk47
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Mysterious Puzzle
--
Chapters
00:00 Question
00:38 Accepted answer (Score 281)
01:17 Answer 2 (Score 64)
01:32 Answer 3 (Score 12)
01:46 Thank you
--
Full question
https://stackoverflow.com/questions/1190...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #python3x
#avk47
ACCEPTED ANSWER
Score 285
In order for you to modify test1 while inside a function you will need to do define test1 as a global variable, for example:
test1 = 0
def test_func():
global test1
test1 += 1
test_func()
However, if you only need to read the global variable you can print it without using the keyword global, like so:
test1 = 0
def test_func():
print(test1)
test_func()
But whenever you need to modify a global variable you must use the keyword global.
ANSWER 2
Score 65
Best solution: Don't use globals
>>> test1 = 0
>>> def test_func(x):
return x + 1
>>> test1 = test_func(test1)
>>> test1
1
ANSWER 3
Score 12
You have to specify that test1 is global:
test1 = 0
def test_func():
global test1
test1 += 1
test_func()