Python Import Statements: A Guide (2024)

The Python import statement lets you import a module into your code. A module is a file that contains functions and values that you can reference from your program. The import statement syntax is: import modulename.

Python is accompanied by a number of built-in modules that allow you to perform common operations in your code. int(), for example, converts a value to an integer. sum() calculates the sum of all items in a list.

Find your bootcamp match

GET MATCHED

By continuing you agree to our Terms of Service and Privacy Policy, and you consent to receive offers and opportunitiesfrom Career Karma by telephone, text message, and email.

X

By continuing you agree to our Terms of Service and Privacy Policy, and you consent to receive offers and opportunities from Career Karma by telephone, text message, and email.

While these functions can be useful, you may want to define your own that can be used throughout your codebase. That’s where Python modules come in.

We’re going to discuss the basics of Python modules. We’ll also discuss how to import a module into your code using the Python import statement.

What is a Python Module?

Python modules are .py files that contain Python code.Any Python file can be a module. Modules are used to group together related code in a project so you can reuse the same code in different files.

Modules, sometimes called packages, allow you to reference pre-written code that can perform common tasks that come up in many of your programs.

For instance, say you are building a complex program that needs to read a lot of data from a file. You could write a module to perform that action. This means that you can store the file reading code elsewhere, which will help you make your main program easier to read.

To access a module in Python, you can use the import statement. The import statement reads the code in a Python module and allows you to use it in another file.

Many of the modules you can use in your programs are part of the Python Standard Library. This library is part of every Python instance. You can import a module contained in the Python Standard Library without installing a module into your system. You can also use pip to install modules, or even create your own.

How to Use the Python import Statement

The Python import statement imports code from one module into another program. You can import all the code from a module by specifying the import keyword followed by the module you want to import.

import statements appear at the top of a Python file, beneath any comments that may exist. This is because importing modules or packages at the top of a file makes the structure of your code clearer.

The syntax for the import statement is:

import [module]

Let’s look at an example of the Python import statement.

If we wanted to import the sys library, we could use:

import sys

Python import Module Example

Suppose we want to import the module called time into a program. The time module is part of the Python Standard Library, so we do not need to install it into our code.

We could import the module using the following code:

import time

Now that we have imported this module, we can access it in our code. In the above example, we have imported time into our code, so now we can access all the time functions in our main program.

To use the code in a module, we need to reference the unique namespace for the module. We can do so by using the dot notation.

Suppose we want to use the sleep() function in the time module. We could do so using this code:

import timetime.sleep(3)

We first import the time module. Python finds the module in the standard library and imports its code.

Then, we use “time.sleep” to reference the sleep() function defined in the time library. Dot notation, then, is where the module name is called, followed by a dot, then the name of the function we want to access.

Our code will wait three seconds and then the program will finish.

If you’re interested in learning more about how the Python time module works, read our beginner’s guide to Python time.

import Python: Add Multiple Modules

So far, we have imported one module into our code. However, we can import as many modules as we want.

Suppose we want to import the time and random modules (which are both part of the Python Standard Library) into our code. We could do so using this code:

import timeimport random

Now that we have imported these modules, we can use their Python functions in our code. Suppose we want to generate a random number between 1 and 10, then get the current time. We could do so using this program:

import timeimport randomprint(random.randint(1, 10))timestamp = time.time()current_time = time.ctime(timestamp)print(current_time)

Our Python program returns:

Python Import Statements: A Guide (1)

"Career Karma entered my life when I needed it most and quickly helped me match with a bootcamp. Two months after graduating, I found my dream job that aligned with my values and goals in life!"

Venus, Software Engineer at Rockbot

4Fri Apr 17 08:09:22 2020

We first import the “time” and “random” modules. Then, we use the random.randint() function to generate a random number. Next, we use the same code from our earlier example to retrieve the current time and print it to the console.

import Python: Using the from Statement

The import statement allows you to import all the functions from a module into your code.

Often, though, you’ll only want to import a few functions, or just one. If this is the case, you can use the from statement. This lets you import only the exact functions you are going to be using in your code.

The syntax for using the from statement is:

from [module] import [function or value]

Suppose we only want to import the choice() function from the “random” library into our code. We could do so like this:

from random import choicefruits = ["Apple", "Pear", "Banana"]print(choice(fruits))

Our code returns:

Pear

We use the from keyword, followed by random, to tell our program that we want to import a specific function from the “random” module. Then, we use the import keyword to tell our code what function we want to import.

When using the from keyword to import a function, you do not need to write the function using dot notation. As you can see above, instead of using random.choice() to access the random.choice() function from the random module, we just use choice().

To learn more about random.choice(), check out our Python random.choice() guide.

import Python: Module Aliases

The default name given to modules in your code is the name of the module.

However, you can override the default module name using the as keyword. This is useful if the name of a module conflicts with a variable you have declared in your code. It is also useful if you want to reference another module that shares the same name.

Suppose we want to import the time module into your code. We are going to import the time module and give it the alias t. We could do so using this code:

import time as tprint(t.time())

Our code returns:

1587111506.6014798

The time library has been given the alias t. When we want to reference any function in the time library, we must use t and the dot notation.

Conclusion

Importing modules is an important part of working with Python that allows you to call functions that are not part of your main program. The modules you work with can be part of Python, installed using pip, or created by you.

For a challenge, try to import the Python logging module into your code. Then, try to import the random.randint() module into your code. When you’re importing randint(), only import the randint() function. Do not import the whole module. You should use a “from” statement.

After you have imported the randint() function, check if you have imported the module successfully. You can do this using the following code:

print(random.randint(1, 9))

This code should return a random number between one and nine.

This tutorial discussed, with examples, the basics of Python modules and how to import them in your code. Now you’re ready to start importing modules like a professional Python coder!

For guidance on the best Python learning resources, courses, and books, check out our comprehensive How to Learn Python guide.

Python Import Statements: A Guide (2024)
Top Articles
Financial Source - How To Use COT Report In Forex Trading
FAQ: How can I set up the Microsoft Authenticator app on multiple devices?
Tattoo Shops Lansing Il
Craftsman M230 Lawn Mower Oil Change
Botanist Workbench Rs3
Professor Qwertyson
Autobell Car Wash Hickory Reviews
Ub Civil Engineering Flowsheet
Nikki Catsouras Head Cut In Half
Clafi Arab
Tv Schedule Today No Cable
Mndot Road Closures
Culver's Flavor Of The Day Monroe
Synq3 Reviews
Hijab Hookup Trendy
How Much Are Tb Tests At Cvs
Mile Split Fl
Video shows two planes collide while taxiing at airport | CNN
Hocus Pocus Showtimes Near Amstar Cinema 16 - Macon
Las 12 mejores subastas de carros en Los Ángeles, California - Gossip Vehiculos
List of all the Castle's Secret Stars - Super Mario 64 Guide - IGN
1773X To
Conan Exiles: Nahrung und Trinken finden und herstellen
Panic! At The Disco - Spotify Top Songs
Bible Gateway passage: Revelation 3 - New Living Translation
Spn 520211
Is Windbound Multiplayer
Baldur's Gate 3: Should You Obey Vlaakith?
European Wax Center Toms River Reviews
Accuradio Unblocked
Mikayla Campinos: Unveiling The Truth Behind The Leaked Content
Vera Bradley Factory Outlet Sunbury Products
Firefly Festival Logan Iowa
Free Tiktok Likes Compara Smm
Perry Inhofe Mansion
Pipa Mountain Hot Pot渝味晓宇重庆老火锅 Menu
Ucm Black Board
Shiftwizard Login Johnston
O'reilly Auto Parts Ozark Distribution Center Stockton Photos
Solemn Behavior Antonym
8005607994
Pawn Shop Open Now
R/Moissanite
Umiami Sorority Rankings
Paul Shelesh
Memberweb Bw
Dickdrainersx Jessica Marie
Juiced Banned Ad
War Room Pandemic Rumble
New Zero Turn Mowers For Sale Near Me
Fresno Craglist
Latest Posts
Article information

Author: Domingo Moore

Last Updated:

Views: 5647

Rating: 4.2 / 5 (53 voted)

Reviews: 84% of readers found this page helpful

Author information

Name: Domingo Moore

Birthday: 1997-05-20

Address: 6485 Kohler Route, Antonioton, VT 77375-0299

Phone: +3213869077934

Job: Sales Analyst

Hobby: Kayaking, Roller skating, Cabaret, Rugby, Homebrewing, Creative writing, amateur radio

Introduction: My name is Domingo Moore, I am a attractive, gorgeous, funny, jolly, spotless, nice, fantastic person who loves writing and wants to share my knowledge and understanding with you.