An example of conditional execution.

Save the version of this code. The Jupyter (*.ipynb) notebook will not be adequate in demonstrating this feature.

Pretend this file is destined to be filled with useful financial functions. We start with an interest accruing function called add_interest.

In addition to that function, we also have main() which has code to test the functionality of add_interest. We give it two values for balance and rate 1000 and 0.05 (\$1000 and 5\%) and check that the result makes sense by comparing it against the known value of this calculation, `1050` ($1050). This is a form of unit testing.

We want to be importable into other programs so they can use add_interest, but we don't want main() and the test it performs to be executed with the import happens (thorough testing on large programs can take many minutes, so testing upon import is a silly idea).

Using the top-level namespace, we notice that a running program has its namespace named __main__, stored in a variable called __name__. We check that variable and only execute the program if the namespace is called that. If a program is imported as a module, its __name__ now contains the name of the file that it imported from, e.g. __name__ = financial.

In [ ]:
def add_interest(balance, rate):
    new_balance = balance * (1 + rate)
    return new_balance

def main():
    amount = 1000
    rate= 0.05
    amount = add_interest(amount, rate)
    if amount == 1050.0:
        print("Test succeeded! Returned (${0:0.2f})".format(amount))
        print("Test failed! Returned (${0:0.2f})".format(amount))

# Conditional Execution
if __name__ == "__main__":