Python modules

| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |

👻 Check our latest review to choose the best laptop for Machine Learning engineers and Deep learning tasks!

Example :

# Simple module, calc.py

def add (x, y):

return (x + y)

def subtract (x, y):

return (x - y)

import statement
We can use any Python source file as a module by executing an import statement in another source Python file.
When the interpreter encounters an import statement, it imports the module if the module is present in the search path. Search path — this is a list of directories that the interpreter looks for to import a module. For example, to import the calc.py module, we need to place the following command at the top of the script:

# calc.py importer

import calc

print add ( 10 , 2 )

Output:

 12 

statement from import

The Python from statement allows you to import certain attributes from a module. from .. import .. has the following syntax:

Output:

 4.0 720 

dir () function
The dir () built-in function returns a sorted list of strings containing the names defined by the module. The list contains the names of all modules, variables and functions that are defined in the module.

# importing sqrt () and factorial from
# math module

from math import sqrt, factorial


# if we just "import math" then
# math.sqrt (16) and math.factorial ()
# required.

print sqrt ( 16 )

print factorial ( 6 )

# Import inline module into random

import random

print dir (math)

Output:

 [’BPF’,’ LOG4’, ’NV_MAGICCONST’,’ RECIP_BPF’, ’Random’,’ SG_MAGICCONST’, ’SystemRandom’,’ TWOPI’, ’WichmannHill’,’ _BuiltinMethodType’, ’_MethodType’,’ __all__’, ’__builtins__’,’ __doc__’, ’__file__’,’ __name__’, ’__package__’,’ _acos’, ’_ceil’, _e _cos’, ’,’ _exp’, ’_hashlib’,’ _hexlify’, ’_inst’,’ _log’, ’_pi’,’ _random’, ’_sin’,’ _sqrt’, ’_test’,’ _test_generator’, ’_urandom’, ’_warn’,’ betavariate’, ’choice’,’ division’, ’expovariate’,’ gammavariate’, ’gauss’,’ getrandbits’ , ’getstate’,’ jumpahead’, ’lognormvariate’,’ normalvariate’, ’paretovariate’,’ randint’, ’random’,’ randrange’, ’sample’,’ seed’, ’setstate’,’ shuffle’, ’ triangular’, ’uniform’,’ vonmisesvariate’, ’weibullvariate’] 

Code snippet illustrating built-in Python modules:

# import of the built-in math module

import math


# using the square root function (sqrt)
# in math module

print math.sqrt ( 25 )


# using the pi function containing in the math module

print math.pi


# 2 radians = 114.59 degrees

print math.degrees ( 2 )


# 60 degrees = 1.04 radians

print math.radians ( 60 )


# Sine 2 radians

print math.sin ( 2 )


# Cosine 0.5 radians

print math.cos ( 0.5 )


# 0.23 radian tangent

print math.tan ( 0.23 )


# 1 * 2 * 3 * 4 = 24

print math.factorial ( 4 )


# imports the inline module into random

import random


# print a random integer from 0 to 5

print random.randint ( 0 , 5 )


# print a random floating point number from 0 to 1

print random.random ()


# random number from 0 to 100

print random.random () * 100

List = [ 1 , 4 , True , 800 , "python" , 27 , "hello" ]


# using the pick function in a random module to select
# random element from a set such as a list

print random.choice ( List )


# import inline datetime module

import datetime

from datetime import date

import time


# Returns the number of seconds since
# Unix Epoch Jan 1, 1970

print time.time ()


# Converts the number of seconds to a date object

print date.fromtimestamp ( 454554 )

Output:

 5.0 3.14159265359 114.591559026 1.0471975512 0.909297426826 0.87758256189 0.234143362351 24 3 0.401533172951 88.4917616788 True 1461425771.87 1970-01-06 
amp-youtube data-videoid = nfYZL-uFm-c layout = responsive width = 665 height = 374>

This article prev left by Gaurav Shrestha . Please post comments if you find something wrong or if you would like to share additional information on the topic discussed above. If you like Python.Engineering and would like to contribute, you can also write an article and mail it to [email protected] See your article appearing on the Python.Engineering homepage and help other geeks.

👻 Read also: what is the best laptop for engineering students?

We hope this article has helped you to resolve the problem. Apart from Python modules, check other Angular by Google JavaScript library-related topics.

Want to excel in Python? See our review of the best Python online courses 2023. If you are interested in Data Science, check also how to learn programming in R.

By the way, this material is also available in other languages:



Frank Porretti

Singapore | 2023-04-01

I was preparing for my coding interview, thanks for clarifying this - Python modules in Python is not the simplest one. I am just not quite sure it is the best method

Anna OConnell

New York | 2023-04-01

I was preparing for my coding interview, thanks for clarifying this - Python modules in Python is not the simplest one. Checked yesterday, it works!

Ken Sikorski

Boston | 2023-04-01

Maybe there are another answers? What Python modules exactly means?. I am just not quite sure it is the best method

Shop

Gifts for programmers

Learn programming in R: courses

$FREE
Gifts for programmers

Best Python online courses for 2022

$FREE
Gifts for programmers

Best laptop for Fortnite

$399+
Gifts for programmers

Best laptop for Excel

$
Gifts for programmers

Best laptop for Solidworks

$399+
Gifts for programmers

Best laptop for Roblox

$399+
Gifts for programmers

Best computer for crypto mining

$499+
Gifts for programmers

Best laptop for Sims 4

$

Latest questions

PythonStackOverflow

Common xlabel/ylabel for matplotlib subplots

1947 answers

PythonStackOverflow

Check if one list is a subset of another in Python

1173 answers

PythonStackOverflow

How to specify multiple return types using type-hints

1002 answers

PythonStackOverflow

Printing words vertically in Python

909 answers

PythonStackOverflow

Python Extract words from a given string

798 answers

PythonStackOverflow

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

606 answers

PythonStackOverflow

Python os.path.join () method

384 answers

PythonStackOverflow

Flake8: Ignore specific warning for entire file

360 answers

News


Wiki

Python | How to copy data from one Excel sheet to another

Common xlabel/ylabel for matplotlib subplots

Check if one list is a subset of another in Python

How to specify multiple return types using type-hints

Printing words vertically in Python

Python Extract words from a given string

Cyclic redundancy check in Python

Finding mean, median, mode in Python without libraries

Python add suffix / add prefix to strings in a list

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

Python - Move item to the end of the list

Python - Print list vertically