Python – Modules

Hello Friends,

Today in this article we are going to discuss about modules.

What are modules?

A Python module is a file containing Python definitions and statements. Can be imported and written in our code.

User defined Modules

Python files which are imported in to the top-level file, or among each other, and provide separate functionalities. 

For reducing lines of code, saving time and doing efficient programming. The user can import the module rather than copying there definitions into different programs.

Creating the Module

## Program to demonstrate way to create module 
total = 0
def square():
    side = int (input ("Enter the side of a square: " ))
    perimeter = 4*side
    print("Perimeter of a square : ",perimeter)

def rectangle():
    lenght = int (input ("Enter the lenght of a square: " ))
    width = int (input ("Enter the width of a square: " ))
    perimeter = 2*(lenght*width)
    print("The perimeter of rectangle is ",perimeter)

def triangle():
    s1 = int (input ("Enter the first of a triangle: " ))
    s2 = int (input ("Enter the second of a triangle: " ))
    s3 = int (input ("Enter the third of a triangle: " ))
    perimeter = s1+s2+s3
    print("The perimeter of triangle is ",perimeter)

The above module creates the four function named add, sub, multi and div. All the four functions have two input arguments “a” and “b” and return the result according to the name of the function.

Now, how to publish our own module publicly in PYPI – Python Packages Index – will discuss in next article.

Now we will see that how to display the content of the user defined module –

To see the content we use dir() which is inbuilt function

# Program to display the content of the user defined module
import pandas
['BooleanDtype', 'Categorical', 'CategoricalDtype', 'CategoricalIndex', 'DataFrame', 'DateOffset', 'DatetimeIndex', 'DatetimeTZDtype', 'ExcelFile', 'ExcelWriter', 'Flags', 'Float32Dtype', 'Float64Dtype', 'Float64Index', 'Grouper', 'HDFStore', 'Index', 'IndexSlice', 'Int16Dtype', 'Int32Dtype', 'Int64Dtype', 'Int64Index', 'Int8Dtype', 'Interval', 'IntervalDtype', 'IntervalIndex', 'MultiIndex', 'NA', 'NaT', 'NamedAgg', 'Period', 'PeriodDtype', 'PeriodIndex', 'RangeIndex', 'Series', 'SparseDtype', 'StringDtype', 'Timedelta', 'TimedeltaIndex', 'Timestamp', 'UInt16Dtype', 'UInt32Dtype', 'UInt64Dtype', 'UInt64Index', 'UInt8Dtype', '__all__', '__builtins__', '__cached__', '__deprecated_num_index_names', '__dir__', '__doc__', '__docformat__', '__file__', '__getattr__', '__git_version__', '__loader__', '__name__', '__package__', '__path__', '__spec__', '__version__', '_config', '_is_numpy_dev', '_libs', '_testing', '_typing', '_version', 'api', 'array', 'arrays', 'bdate_range', 'compat', 'concat', 'core', 'crosstab', 'cut', 'date_range', 'describe_option', 'errors', 'eval', 'factorize', 'get_dummies', 'get_option', 'infer_freq', 'interval_range', 'io', 'isna', 'isnull', 'json_normalize', 'lreshape', 'melt', 'merge', 'merge_asof', 'merge_ordered', 'notna', 'notnull', 'offsets', 'option_context', 'options', 'pandas', 'period_range', 'pivot', 'pivot_table', 'plotting', 'qcut', 'read_clipboard', 'read_csv', 'read_excel', 'read_feather', 'read_fwf', 'read_gbq', 'read_hdf', 'read_html', 'read_json', 'read_orc', 'read_parquet', 'read_pickle', 'read_sas', 'read_spss', 'read_sql', 'read_sql_query', 'read_sql_table', 'read_stata', 'read_table', 'read_xml', 'reset_option', 'set_eng_float_format', 'set_option', 'show_versions', 'test', 'testing', 'timedelta_range', 'to_datetime', 'to_numeric', 'to_pickle', 'to_timedelta', 'tseries', 'unique', 'util', 'value_counts', 'wide_to_long']

Importing the module

import random
random.randint(20, 100)
print(random.randint(20, 100)

Second output

import random
random.randint(20, 100)
print(random.randint(20, 100)

The random function from random module changes the output between 20 and 100

Renaming the Module and use new name in module

import random as r
r.randint(20, 100)

Thank you

Have a nice day

You may also like...

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: