The Python Oracle

Local (?) variable referenced before assignment

--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Mysterious Puzzle

--

Chapters
00:00 Local (?) Variable Referenced Before Assignment
00:27 Answer 1 Score 12
00:38 Accepted Answer Score 285
01:03 Answer 3 Score 65
01:13 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()