A function that can count how many times it’s been called.

A variable created inside a function is called a local variable. For example, the function myPrint in Variable number contained the local variables listOfStrings and oneBigString. It’s called a local variable because the name of a local variable cannot be mentioned outside the function in which the local variable was created.

A local variable gets destroyed when we return from the function. In other words, the function gets amnesia when we return from it. The variable is recreated with a new value if we call the function again. In other words, the reincarnated function retains no memory of its previous incarnation. A function that has to count how many times it’s been called can therefore not rely on information stored in its own local variables.

A variable that is not created inside a function (or inside a class definition, which we’ll do later) is called a global variable. Fortunately, we have already seen that a function can mention a global variable. For example, the function verse in Define a function mentions the global variable verses, and the function score in the poker example in Sort mentions the global variable increasing. These two functions read their global variables, but did not attempt to write the variables.

But if the function wants to write a global variable, and not merely read it, then the function must include the global statement in line 13 of countcalls.py.

I’m writing a function that counts how many times it’s been called because this is the simplest example of a function that needs to write as well as read a global variable.

countcalls.py

This is call number 1.
This is call number 2.
This is call number 3.

Things to try

  1. What will happen if a local variable and a global variable have the same name? Let’s avoid this problem by giving short name to the local variables (i, n, s, name) and longer names to the global variables (callCount, maxLen, increasingRank). As George Orwell said in the appendix of Nineteen Eighty-Four, “The B words were in all cases compound words.”

  2. Not satisfied with avoiding the problem? Here’s the answer. If you do have a local variable and a global variable with the same name, the local variable eclipses the global variable.
    i = 10   #ill-advised name for a global variable
    
    def myFunc():
        i = 20     #Create a local variable.
        print(i)   #It prints the local variable.
    
    myFunc()
    
    20