I believe Python uses a scope of possibilities for local variables. That is, in any given function, if you assign a value to a local variable, it will be available from now on and within this function until it returns. Therefore, since both branches of your code are guaranteed to be assigned to a , there is no need to first assign None to a .
Note that when you can also access variables declared in external functions, in other words, Python has closures.
def adder(first): def add(second): return first + second return add
This defines a function called an adder. When called with the first argument, it returns a function that adds any argument that it receives to first and returns that value. For example:
add_two = adder(2) add_three = adder(3) add_two(4)
However, although you can read the value from an external function, you cannot change it (unlike many other languages). For example, imagine trying to implement a drive. You can write code like this:
def accumulator(): total = 0 def add(number): total += number return total return add
Unfortunately, when trying to use this code, an error message appears:
UnboundLocalError: local variable 'total' referenced before assignment
This is because the line total += number tries to change the value of total , which cannot be done this way in Python.
Michael williamson
source share