Q:

Does global variable used in a function need to be defined before the def block?

I must admit that I didn't expect the following code could work (code sample from a collegue of mine):
def foo():
    li.append(3)
li = [1, 2]
foo()
print(li) # gives [1, 2, 3]

My questions are:

why is 'global li' not needed in the 'def foo()'?
why is 'li = [1, 2]' not needed to be put before the 'def foo()'?

ps. Python 3.6.1 is used for the listed code sample.

A:

Global keyword is a keyword that allows a user to modify a variable outside of the current scope.
Rules of global keyword:

If a variable is assigned a value anywhere within the function’s
body, it’s assumed to be a local unless explicitly declared as
global.
Variables that are only referenced inside a function are
implicitly global.  
We Use global keyword to use a global variable       inside a
function.
There is no need to use global keyword outside a      function.

Your code , you are not changing or assigning a 'li' value
2.Here list is defined before foo() is called, so it working fine.suppose if you call foo() before li is defined, it will throw a error like NameError: name 'li' is not defined

