Global names
A scope is the part of a program where a name can be used. Python keeps names in namespaces: one global namespace for the whole file, plus a fresh local namespace each time a function is called.
Line 1 runs at the top level of the file, outside any function. So = stores 10 under the name count in the global namespace. Every line of this file can read it.
def builds a function and stores it under the global name add. The indented body, lines 3 and 4, does not run yet: it waits until someone calls add().
Inside a call
Line 5 calls add(5). Python jumps into the function and makes a new, empty local namespace for this one call. The parameter n is a local name, and it gets the argument 5.
Line 3 needs count. Python looks in the local namespace first: no count there. Then it looks in the global namespace and finds 10. Reading a global name inside a function just works.
count + n is 10 + 5, which is 15. Because = runs inside the function, total becomes a local name. It lives in this call's namespace only; the global namespace never sees it.
The rule: a name you assign anywhere in a function is local to that whole function. So count = count + n would fail with UnboundLocalError. To change the global count, write global count first.
After the call
return total hands 15 back to line 5, and = stores it under the global name answer. The call is over, so Python forgets its local namespace: n and total are gone.
Line 6 is at the top level, so Python looks answer up in the global namespace, finds 15 and prints it.
Line 7 asks for total at the top level. Python searches the global names, then the built-in ones: no total anywhere. It only ever lived inside the finished call, so Python stops with a NameError.
Try it yourself
;; step 1/10
# global: made at the top level of the file
count = 10
def add(n):
# local: made inside the function
total = count + n
return total
Python looks a name up in up to four scopes, innermost first: the local one, the enclosing functions (when a def sits inside another def), the global one (the module) and the built-in names such as print and len. People remember the order as LEGB. The Python tutorial says the local namespace is created when the function is called and deleted (better: forgotten) when it returns or raises an exception it does not handle. Each call gets its own fresh one.