Python – Modules and Packages Example

Sometimes we want to modularize our code, and group code into modules or packages for reusability & organizational purposes.

# from

def my_function():
    print("Hello From My Function!")

def my_function_with_args(username, greeting):
    print("Hello, {} , From My Function!, I wish you {}"
        .format(username, greeting))

def sum_two_numbers(a, b):
    return a + b

# from in same folder

import lib

if __name__ == "__main__":

    #prints - "Hello, John Doe, From My Function!, I wish you a great year!"
    lib.my_function_with_args("John Doe", "a great year!")

    # after this line x will hold the value 3!
    x = lib.sum_two_numbers(1,2)

Now, when we run the main function and call “lib.my_function()” for example, it will run my_function() from the file in the same directory.

Leave a Reply