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
What Happens If I Pay 2 Extra Mortgage Payments a Year?
Wat is het meest vertaalde boek ter wereld?
Frederick County Craigslist
Cash4Life Maryland Winning Numbers
FFXIV Immortal Flames Hunting Log Guide
Is Sportsurge Safe and Legal in 2024? Any Alternatives?
Obituary (Binghamton Press & Sun-Bulletin): Tully Area Historical Society
Klustron 9
Craigslist Cars And Trucks Buffalo Ny
4302024447
Aktuelle Fahrzeuge von Autohaus Schlögl GmbH & Co. KG in Traunreut
Walmart Windshield Wiper Blades
Nene25 Sports
6813472639
Kitty Piggy Ssbbw
2016 Hyundai Sonata Refrigerant Capacity
Lcwc 911 Live Incident List Live Status
Aaa Saugus Ma Appointment
Teacup Yorkie For Sale Up To $400 In South Carolina
Music Go Round Music Store
Program Logistics and Property Manager - Baghdad, Iraq
Georgetown 10 Day Weather
A Biomass Pyramid Of An Ecosystem Is Shown.Tertiary ConsumersSecondary ConsumersPrimary ConsumersProducersWhich
Munis Self Service Brockton
Toothio Login
Anonib Oviedo
At 25 Years, Understanding The Longevity Of Craigslist
Mdt Bus Tracker 27
Ticket To Paradise Showtimes Near Cinemark Mall Del Norte
Remnants of Filth: Yuwu (Novel) Vol. 4
Airg Com Chat
Human Unitec International Inc (HMNU) Stock Price History Chart & Technical Analysis Graph - TipRanks.com
Skyrim:Elder Knowledge - The Unofficial Elder Scrolls Pages (UESP)
Enjoy4Fun Uno
Dmitri Wartranslated
Shoecarnival Com Careers
Wordle Feb 27 Mashable
2Nd Corinthians 5 Nlt
Hampton In And Suites Near Me
Wolf Of Wallstreet 123 Movies
Backpage New York | massage in New York, New York
Bradshaw And Range Obituaries
Quest Diagnostics Mt Morris Appointment
Rubmaps H
Concentrix + Webhelp devient Concentrix
Goosetown Communications Guilford Ct
Grace Charis Shagmag
Minecraft Enchantment Calculator - calculattor.com
Ok-Selection9999
Primary Care in Nashville & Southern KY | Tristar Medical Group
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.