alternative
  • Home (current)
  • About
  • Tutorial
    Technologies
    C#
    Deep Learning
    Statistics for AIML
    Natural Language Processing
    Machine Learning
    SQL -Structured Query Language
    Python
    Ethical Hacking
    Placement Preparation
    Quantitative Aptitude
    View All Tutorial
  • Quiz
    C#
    SQL -Structured Query Language
    Quantitative Aptitude
    Java
    View All Quiz Course
  • Q & A
    C#
    Quantitative Aptitude
    Java
    View All Q & A course
  • Programs
  • Articles
    Identity And Access Management
    Artificial Intelligence & Machine Learning Project
    How to publish your local website on github pages with a custom domain name?
    How to download and install Xampp on Window Operating System ?
    How To Download And Install MySql Workbench
    How to install Pycharm ?
    How to install Python ?
    How to download and install Visual Studio IDE taking an example of C# (C Sharp)
    View All Post
  • Tools
    Program Compiler
    Sql Compiler
    Replace Multiple Text
    Meta Data From Multiple Url
  • Contact
  • User
    Login
    Register

Python - Python Advanced - Module Tutorial

A python file with extension .py and containing a set of functions, classes, and variables are called a module. And file name is called as the module name.

We use modules to break down large programs into small manageable and organized files. Furthermore, modules provide reusability of code.

 

Types of modules-

1. built-in - math, NumPy, matplotlib, etc.

2. user defines - any function which is defined by the user.

 

Creating a module

Creating a simple user define a module to perform arithmetic calculations with the name mycalc.py

def add(x,y):
    return (x+y)

def subtract(x,y):
    return (x-y)

def multiply(x,y):
    return (x*y)

def divide(x,y):
    return (x/y)

def modulus(x,y):
    return (x%y)

pi = 3.4

 

Importing a module

We can import functions, classes, and variables from one module to another module or the interactive interpreter in Python using the import statement

Syntax-

import module_name

Where module_name is a file name having a .py extension, which includes function, classes, and variables.

This does not import the functions or classes directly instead imports the module only

We can access functions, classes, and variables using dot. operator.

Example-

# importing module mycalc.py
import mycalc

print(mycalc.add(4,3))
print(mycalc.subtract(4,3))
print(mycalc.multiply(4,3))
print(mycalc.divide(4,3))
print(mycalc.modulus(4,3))
print(mycalc.pi)

Output-

7
1
12
1.3333333333333333
1
3.14

 

From import statement

Python from import statement let you import specific attributes from a module without importing the module as a whole.

Syntax-

from module_name import attribute_name1, attribute_name2….

Example-

# importing add function only from module mycalc.py

from mycalc import add,pi
print(add(7,5))
print(pi)
print(subtract(7,5))

Output-

12
3.14
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Input In [8], in <cell line: 5>()
      3 print(add(7,5))
      4 print(pi)
----> 5 print(subtract(7,5))

NameError: name 'subtract' is not defined

If we call a function other than the defined one using the from import statement, it will throw a NameError.
After importing a specific attribute from the module, we need to call it using attribute_name, not using module_name.attribute_name

 
To import all the attribute from module use asterick *
Syntax-
from module_name import *
Example-
# importing all attribute from module mycalc.py

from mycalc import *
print(add(4,5))
print(pi)
print(subtract(4,5))
Output-
9
3.14
-1
Using asterick *  , is not a good programming practice. This can lead to duplicate definitions for an identifier.

For example built in module name math also has pi variable and user defined module mycalc also has pi variable.which leads to duplicate and cause ambiguity.

 

dir() built-in function

It is built-in function to list all the function names (or variable names) in a module.
Example-
import math
print(dir(math))
print(math.__name__)
print(math.__doc__)
Output-
['__doc__', '__loader__', '__name__', '__package__', '__spec__', 'acos',
 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'comb',
 'copysign', 'cos', 'cosh', 'degrees', 'dist', 'e', 'erf', 'erfc',
 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum',
 'gamma', 'gcd', 'hypot', 'inf', 'isclose', 'isfinite', 'isinf', 'isnan',
 'isqrt', 'lcm', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'log2',
 'modf', 'nan', 'nextafter', 'perm', 'pi', 'pow', 'prod', 'radians',
 'remainder', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'tau', 'trunc', 'ulp']

math

This module provides access to the mathematical functions
defined by the C standard.

 

All other names that begin and end with __ (double underscore) are built-in attributes associated with the module, that provides the info about the module.

Example-
  • __name__ will provide the name of the module

  • __doc__ will provide the documentation of a module

Python

Python

  • Introduction
  • Installation and running a first python program
    • How to install Python ?
    • Running 1st Hello World Python Program
    • How to install Pycharm ?
  • Things to know before proceed
    • Escape Characters/Special Characters
    • Syntax ( Indentation, Comments )
    • Variable
    • Datatype
    • Keyword
    • Literals
    • Operator
    • Precedence & Associativity Of Operator
    • Identifiers
    • Ascii, Binary, Octal, Hexadecimal
    • TypeCasting
    • Input, Output Function and Formatting
  • Decision control and looping statement
    • if-else
    • for loop
    • While loop
    • Break Statement
    • Continue Statement
    • Pass Statement
  • Datatype
    • Number
    • List
    • Tuple
    • Dictionary
    • String
    • Set
    • None & Boolean
  • String Method
    • capitalize()
    • upper()
    • lower()
    • swapcase()
    • casefold()
    • count()
    • center()
    • endswith()
    • split()
    • rsplit()
    • title()
    • strip()
    • lstrip()
    • rstrip()
    • find()
    • index()
    • format()
    • encode()
    • expandtabs()
    • format_map()
    • join()
    • ljust()
    • rjust()
    • maketrans()
    • partition()
    • rpartition()
    • translate()
    • splitlines()
    • zfill()
    • isalpha()
    • isalnum()
    • isdecimal()
    • isdigit()
    • isidentifier()
    • islower()
    • isupper()
    • isnumeric()
    • isprintable()
    • isspace()
    • istitle()
  • Python Function
    • Introduction
  • Lambda Function
    • Lambda Function
  • Python Advanced
    • Iterators
    • Module
    • File Handling
    • Exceptional Handling
    • RegEx - Regular Expression
    • Numpy
    • Pandas

About Fresherbell

Best learning portal that provides you great learning experience of various technologies with modern compilation tools and technique

Important Links

Don't hesitate to give us a call or send us a contact form message

Terms & Conditions
Privacy Policy
Contact Us

Social Media

© Untitled. All rights reserved. Demo Images: Unsplash. Design: HTML5 UP.

Toggle