Create a simple Python module that can print out two Christmas patterns.

Welcome to the second blog of Christmas!

On the second day of Christmas my true love sent to me
two functions in a module
and a micro:bit in a Christmas tree

A module is a piece of Python code containing things such as functions, classes and variables that can be imported into Python programs. Python comes with many built-in modules, such as time and turtle. Today you’re going to create a simple module.

Firstly create a new Python script and add the following code:

def tree():
    print("          *")
    print("         *o*")
    print("        *o*o*")
    print("       ***o***")
    print("      **o**o*o*")
    print("     **o**o**o**")
    print("    **o**o***o*o*")
    print("   *****o*o**o****")
    print("  **o**o*****o**o**")
    print(" ******o*****o**o***")
    print("****o***o**o***o***o*")
    print("     ____!_!____")
    print("     \_________/")

def gift():
    print("       _   _")
    print("      ((\o/))")
    print(" .-----//^\\-----.")
    print(" |    /`| |`\    |")
    print(" |      | |      |")
    print(" |      | |      |")
    print(" |      | |      |")
    print(" '------===------'")

As you can see, the code is simply two functions called ‘tree’ and ‘gift’ that print pictures of a Christmas tree and a gift. This is going to be our module. Save your script as ‘christmas_patterns’. Now you need to create another script, with this code:

import christmas_patterns
christmas_patterns.tree()
christmas_patterns.gift()

In the code we import our module and then run our ‘tree’ and ‘gift’ functions from inside the module. Save your file as ‘test’, making sure you save it in the same directory as your module. For example, if you saved your module in the Python34 folder (the default save location), you must also save your test script here.

Now you can run your test script. You should see a picture of a Christmas tree and a gift printed out. Congratulations! You’ve just created your first module. Now you can create more scripts that use your module, as long as they’re in the same directory. Merry Christmas!

Advertisements