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?

Python modules ceil: Questions

Is there a ceiling equivalent of // operator in Python?

1 answers

I found out about the // operator in Python which in Python 3 does division with floor.

Is there an operator which divides with ceil instead? (I know about the / operator which in Python 3 does floating point division.)

165

Answer #1

You can just do upside-down floor division:

def ceildiv(a, b):
    return -(-a // b)

This works because Python"s division operator does floor division (unlike in C, where integer division truncates the fractional part).

This also works with Python"s big integers, because there"s no (lossy) floating-point conversion.

Here"s a demonstration:

>>> from __future__ import division   # a/b is float division
>>> from math import ceil
>>> b = 3
>>> for a in range(-7, 8):
...     print(["%d/%d" % (a, b), int(ceil(a / b)), -(-a // b)])
... 
["-7/3", -2, -2]
["-6/3", -2, -2]
["-5/3", -1, -1]
["-4/3", -1, -1]
["-3/3", -1, -1]
["-2/3", 0, 0]
["-1/3", 0, 0]
["0/3", 0, 0]
["1/3", 1, 1]
["2/3", 1, 1]
["3/3", 1, 1]
["4/3", 2, 2]
["5/3", 2, 2]
["6/3", 2, 2]
["7/3", 3, 3]

cos

How do I install pip on macOS or OS X?

5 answers

I spent most of the day yesterday searching for a clear answer for installing pip (package manager for Python). I can"t find a good solution.

How do I install it?

1672

Answer #1

UPDATE (Jan 2019):

easy_install has been deprecated. Please use get-pip.py instead.


Old answer:

easy_install pip

If you need admin privileges to run this, try:

sudo easy_install pip

1672

Answer #2

⚡️ TL;DR — One line solution.

All you have to do is:

sudo easy_install pip

2019: ⚠️easy_install has been deprecated. Check Method #2 below for preferred installation!

Details:

⚡️ OK, I read the solutions given above, but here"s an EASY solution to install pip.

MacOS comes with Python installed. But to make sure that you have Python installed open the terminal and run the following command.

python --version

If this command returns a version number that means Python exists. Which also means that you already have access to easy_install considering you are using macOS/OSX.

ℹ️ Now, all you have to do is run the following command.

sudo easy_install pip

After that, pip will be installed and you"ll be able to use it for installing other packages.

Let me know if you have any problems installing pip this way.

Cheers!

P.S. I ended up blogging a post about it. QuickTip: How Do I Install pip on macOS or OS X?


✅ UPDATE (Jan 2019): METHOD #2: Two line solution —

easy_install has been deprecated. Please use get-pip.py instead.

First of all download the get-pip file

curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py

Now run this file to install pip

python get-pip.py

That should do it.

Another gif you said? Here ya go!

1672

Answer #3

You can install it through Homebrew on OS X. Why would you install Python with Homebrew?

The version of Python that ships with OS X is great for learning but it’s not good for development. The version shipped with OS X may be out of date from the official current Python release, which is considered the stable production version. (source)

Homebrew is something of a package manager for OS X. Find more details on the Homebrew page. Once Homebrew is installed, run the following to install the latest Python, Pip & Setuptools:

brew install python

We hope this article has helped you to resolve the problem. Apart from Python modules, check other ceil-related topics.

Want to excel in Python? See our review of the best Python online courses 2022. 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:



Chen Sikorski

Texas | 2022-12-10

Simply put and clear. Thank you for sharing. Python modules and other issues with Python functions was always my weak point 😁. Will use it in my bachelor thesis

Boris Robinson

Rome | 2022-12-10

Thanks for explaining! I was stuck with Python modules for some hours, finally got it done 🤗. I am just not quite sure it is the best method

Julia Emmerson

New York | 2022-12-10

Maybe there are another answers? What Python modules exactly means?. Will use it in my bachelor thesis

Shop

Learn programming in R: courses

$

Best Python online courses for 2022

$

Best laptop for Fortnite

$

Best laptop for Excel

$

Best laptop for Solidworks

$

Best laptop for Roblox

$

Best computer for crypto mining

$

Best laptop for Sims 4

$

Latest questions

NUMPYNUMPY

Common xlabel/ylabel for matplotlib subplots

12 answers

NUMPYNUMPY

How to specify multiple return types using type-hints

12 answers

NUMPYNUMPY

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

12 answers

NUMPYNUMPY

Flake8: Ignore specific warning for entire file

12 answers

NUMPYNUMPY

glob exclude pattern

12 answers

NUMPYNUMPY

How to avoid HTTP error 429 (Too Many Requests) python

12 answers

NUMPYNUMPY

Python CSV error: line contains NULL byte

12 answers

NUMPYNUMPY

csv.Error: iterator should return strings, not bytes

12 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

sin

How to specify multiple return types using type-hints

exp

Printing words vertically in Python

exp

Python Extract words from a given string

Cyclic redundancy check in Python

Finding mean, median, mode in Python without libraries

cos

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