Codementor Events

Crash Course On Python Modules

Published Aug 15, 2018Last updated Aug 17, 2018

What are Modules?

Modules are the python programs with some functions and variables are defined in it.

What is the importance of Modules?

Modules help us to organize the code in the more better way. And modules are reusable and can be used in different programs.
 Still confusing. Ok, No worries, let’s understand with the help of an example.

Problem Statement — 1 :

  • Create a module to calculate the Multiplication, Division, Addition, and Subtraction of two numbers.
  • Two numbers must be entered by the Users.
  • Use the module in the main file.

Create a new file, calculator.py and write the below into it.

def multiply(number1, number2): 
  return number1 * number2 

def division(number1, number2): 
  return number1/number2 
 
def addition(number1, number2): 
  return number1 + number2 

def subtraction(number1, number2): 
  if number1 > number2: 
    	return number1 - number2 
   else: 
    	return number2 - number1

As you can observe that we define four functions to calculate the Multiplication, Division, Addition, and Subtraction.

This is the module. Is there any difference with the normal python program? Probably not.

Now, our module is ready, the only thing left is to import the module and use these functions in our main program.

Create a file main.py and write the below code into it.

# Import calculator module 
import calculator 

number1 = input("Enter the First Number: ") 
number2 = input("Enter the Second Number: ") 

print("Multiplication of two numbers is : ", calculator.multiply(number1, number2)) 

print("Division of two numbers is : ", calculator.division(number1, number2)) 

print("Addition of two numbers is :", calculator.addition(number1, number2)) 

print("Subtraction of two numbers is :", calculator.subtraction(number1, number2))

Now, it’s time to understand the code.

  • 1stline is to import the Module that we have created earlier. It is pretty easy to import the module.
  • 3rdand 4thare for the user to enter the two numbers.

Pay attention to the statement calculator.multiply(number1, number2). To call the multiply function from calculator module. Just need to write module_name.function_name(). That’s it.

Execute the Program:

python3.6 main.py

Enter the First Number: 10

Enter the Second Number: 7

(‘Multiplication of two numbers is: ‘, 70)

(‘Division of two numbers is: ‘, 1)

(‘Addition of two numbers is:’, 17)

(‘Subtraction of two numbers is:’, 3)

Discover and read more posts from Ashutosh Kukreti
get started
post commentsBe the first to share your opinion
Show more replies