Without scoping

Once you get to writing more and more complex scripts in Python, one thing you will inevitably end up doing is accidentally reusing variable names. This can introduce bugs in your code when you assume a variable is empty and it’s not, etc.. Let’s take the following example:

#   First bit of code
bla = 45

##########################################
#   Pretend there's a lot of code here   #
##########################################

#   Second bit of code that assumes bla is empty
if 'bla' in globals():
    bla += 55
else:
    bla = 55

print("Variable \"bla\" is:", bla)

Result:

Variable "bla" is: 100

With scoping

Let’s put these two blocks of code into two separate functions. Now, each variable is defined within its own little block, and doesn’t exist outside of the block. Another function which checks if it’s there won’t find previous instances of it, so there will be no weird conflicts or bugs.

#   Define first bit of code and run it
def functionOne():
    bla = 45

functionOne()

##########################################
#   Pretend there's a lot of code here   #
##########################################

#   Second bit of code
def functionTwo():
    if 'bla' in locals():
        bla += 55
    else:
        bla = 55

    print("Variable \"bla\" is:", bla)

functionTwo()

Result:

Variable "bla" is: 55