Python Modules (2024)

What is a Module?

Consider a module to be the same as a code library.

A file containing a set of functions you want to include in your application.

Create a Module

To create a module just save the code you want in a file with the file extension .py:

Example

Save this code in a file named mymodule.py

def greeting(name):
print("Hello, " + name)

Use a Module

Now we can use the module we just created, by using the import statement:

Example

Import the module named mymodule, and call the greeting function:

import mymodule

mymodule.greeting("Jonathan")

Run Example »

Note: When using a function from a module, use the syntax: module_name.function_name.

Variables in Module

The module can contain functions, as already described, but also variables of all types (arrays, dictionaries, objects etc):

Example

Save this code in the file mymodule.py

person1 = {
"name": "John",
"age": 36,
"country": "Norway"
}

Example

Import the module named mymodule, and access the person1 dictionary:

import mymodule

a = mymodule.person1["age"]
print(a)

Run Example »

Naming a Module

You can name the module file whatever you like, but it must have the file extension .py

Re-naming a Module

You can create an alias when you import a module, by using the as keyword:

Example

Create an alias for mymodule called mx:

import mymodule as mx

a = mx.person1["age"]
print(a)

Run Example »

Built-in Modules

There are several built-in modules in Python, which you can import whenever you like.

Example

Import and use the platform module:

import platform

x = platform.system()
print(x)

Try it Yourself »

Using the dir() Function

There is a built-in function to list all the function names (or variable names) in a module. The dir() function:

Example

List all the defined names belonging to the platform module:

import platform

x = dir(platform)
print(x)

Try it Yourself »

Note: The dir() function can be used on all modules, also the ones you create yourself.

Import From Module

You can choose to import only parts from a module, by using the from keyword.

Example

The module named mymodule has one function and one dictionary:

def greeting(name):
print("Hello, " + name)

person1 = {
"name": "John",
"age": 36,
"country": "Norway"
}

Example

Import only the person1 dictionary from the module:

from mymodule import person1

print (person1["age"])

Run Example »

Note: When importing using the from keyword, do not use the module name when referring to elements in the module. Example: person1["age"], not mymodule.person1["age"]

W3schools Pathfinder

Track your progress - it's free!

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning.
Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness
of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Copyright 1999-2024 by Refsnes Data. All Rights Reserved.W3Schools is Powered by W3.CSS.

Python Modules (2024)

FAQs

What are the modules in Python? ›

In Python, Modules are simply files with the “. py” extension containing Python code that can be imported inside another Python Modules Operations Program. In simple terms, we can consider a module to be the same as a code library or a file that contains a set of functions that you want to include in your application.

How many modules of Python are there? ›

The Python standard library contains well over 200 modules, although the exact number varies between distributions.

What is a Python module vs package? ›

In Python, both modules and packages organize and structure the code but serve different purposes. In simple terms, a module is a single file containing Python code, whereas a package is a collection of modules that are organized in a directory hierarchy.

How to know the list of modules in Python? ›

To check all the installed Python modules, we can use the following two commands with the 'pip': Using 'pip freeze' command. Using 'pip list command.

Is NumPy a module or package? ›

NumPy is the fundamental package for scientific computing in Python.

Is pandas a module or package? ›

pandas is a Python package providing fast, flexible, and expressive data structures designed to make working with “relational” or “labeled” data both easy and intuitive. It aims to be the fundamental high-level building block for doing practical, real-world data analysis in Python.

What is the most popular module in Python? ›

Top 10 Python Libraries You Must Know In 2024
  • TensorFlow.
  • Scikit-Learn.
  • Numpy.
  • Keras.
  • PyTorch.
  • LightGBM.
  • Eli5.
  • SciPy.
Jul 5, 2024

Should I learn all modules in Python? ›

That's not how it works, you don't have to learn all libraries or modules. No one does. We learn what we need for our job. Instead focus on building something, you may have to use some libraries, and also learn a bit of them.

What is the main module of Python? ›

Python Main Module

Python has no main function or method. Instead, there is a main module. The main module is the source file that runs first. Whatever file you give to the interpreter at startup becomes main.

Is a Python module just a file? ›

Modules are Python files that are intended to be imported into scripts and other modules so that their defined members—like classes and functions—can be used. 04:41 Packages are a collection of related modules that aim to achieve a common goal.

Is every Python file a module? ›

Simply put, a module is a file consisting of Python code. It can define functions, classes, and variables, and can also include runnable code. Any Python file can be referenced as a module. A file containing Python code, for example: test.py , is called a module, and its name would be test .

Is A Python module the same as a class? ›

In Python, when you import a module, you get the module. Unlike some other languages, there is no special relationship between modules and classes. When you write a module, you're allowed to have a class with the same name. You're also allowed to have just one class with a different name.

Why do we need modules in Python? ›

A module can define functions, classes, and variables. A module can also include runnable code. Grouping related code into a module makes the code easier to understand and use. It also makes the code logically organized.

What modules exist in Python? ›

Python Module Index
cmdBuild line-oriented command interpreters.
codeFacilities to implement read-eval-print loops.
codecsEncode and decode data and streams.
codeopCompile (possibly incomplete) Python code.
collectionsContainer datatypes
279 more rows

What is meant by module in Python? ›

Modules in Python are simply files with the “. py” extension that contain Python code such as Python functions, methods, classes, or variables that may be imported into another Python program. A Python module is a file that contains Python commands and definitions.

What is the modulus in Python? ›

The Python Modulo, represented by the symbol %, is a mathematical operator that calculates the remainder of a division operation. Here's a simple example: 10 % 3 would return 1 because dividing 10 by 3 gives you a quotient of 3 and a remainder of 1. The Modulo Operator is not just limited to integers.

What is Python types module? ›

types — Dynamic type creation and names for built-in types. This module defines utility functions to assist in dynamic creation of new types. It also defines names for some object types that are used by the standard Python interpreter, but not exposed as builtins like int or str are.

What are Python modules written in? ›

The library contains built-in modules (written in C) that provide access to system functionality such as file I/O that would otherwise be inaccessible to Python programmers, as well as modules written in Python that provide standardized solutions for many problems that occur in everyday programming.

Top Articles
Amazon Digital and Device Forums
How much historical stock data does Polygon have? | Polygon
Spasa Parish
Rentals for rent in Maastricht
159R Bus Schedule Pdf
Sallisaw Bin Store
Black Adam Showtimes Near Maya Cinemas Delano
Www.myschedule.kp.org
Ascension St. Vincent's Lung Institute - Riverside
Understanding British Money: What's a Quid? A Shilling?
Xenia Canary Dragon Age Origins
Momokun Leaked Controversy - Champion Magazine - Online Magazine
Maine Coon Craigslist
‘An affront to the memories of British sailors’: the lies that sank Hollywood’s sub thriller U-571
Tyreek Hill admits some regrets but calls for officer who restrained him to be fired | CNN
Haverhill, MA Obituaries | Driscoll Funeral Home and Cremation Service
Rogers Breece Obituaries
Ems Isd Skyward Family Access
Elektrische Arbeit W (Kilowattstunden kWh Strompreis Berechnen Berechnung)
Omni Id Portal Waconia
Kellifans.com
Banned in NYC: Airbnb One Year Later
Four-Legged Friday: Meet Tuscaloosa's Adoptable All-Stars Cub & Pickle
Model Center Jasmin
Ice Dodo Unblocked 76
Is Slatt Offensive
Labcorp Locations Near Me
Storm Prediction Center Convective Outlook
Experience the Convenience of Po Box 790010 St Louis Mo
Fungal Symbiote Terraria
modelo julia - PLAYBOARD
Poker News Views Gossip
Abby's Caribbean Cafe
Joanna Gaines Reveals Who Bought the 'Fixer Upper' Lake House and Her Favorite Features of the Milestone Project
Tri-State Dog Racing Results
Navy Qrs Supervisor Answers
Trade Chart Dave Richard
Lincoln Financial Field Section 110
Free Stuff Craigslist Roanoke Va
Stellaris Resolution
Wi Dept Of Regulation & Licensing
Pick N Pull Near Me [Locator Map + Guide + FAQ]
Crystal Westbrooks Nipple
Ice Hockey Dboard
Über 60 Prozent Rabatt auf E-Bikes: Aldi reduziert sämtliche Pedelecs stark im Preis - nur noch für kurze Zeit
Wie blocke ich einen Bot aus Boardman/USA - sellerforum.de
Infinity Pool Showtimes Near Maya Cinemas Bakersfield
Dermpathdiagnostics Com Pay Invoice
How To Use Price Chopper Points At Quiktrip
Maria Butina Bikini
Busted Newspaper Zapata Tx
Latest Posts
Article information

Author: Manual Maggio

Last Updated:

Views: 6231

Rating: 4.9 / 5 (49 voted)

Reviews: 80% of readers found this page helpful

Author information

Name: Manual Maggio

Birthday: 1998-01-20

Address: 359 Kelvin Stream, Lake Eldonview, MT 33517-1242

Phone: +577037762465

Job: Product Hospitality Supervisor

Hobby: Gardening, Web surfing, Video gaming, Amateur radio, Flag Football, Reading, Table tennis

Introduction: My name is Manual Maggio, I am a thankful, tender, adventurous, delightful, fantastic, proud, graceful person who loves writing and wants to share my knowledge and understanding with you.