Digital Scholarship Resources - Vanderbilt Libraries Digital Scholarship and Communications Office
Previous lesson: Python programming basics
This lesson explains how to import modules from the Python Standard Library. It introduces the concept of methods associated with a class.
Learning objectives At the end of this lesson, the learner will:
.upper()
method to turn a string to all uppercase letters.Total video time: 33m 35s
Lesson Jupyter notebook at GitHub
A module is reusable code stored in a separate file. Functions can be imported from a module using an import
statement.
Modules in the Standard Library are included in the normal Python distribution. Functions in the Standard Libarary that aren’t built-in must be imported.
Forms of the import statement
Import a single function:
from math import sqrt
answer = sqrt(3) # don't need to include the module name
Import the whole module:
import math
answer = math.sqrt(3) # prefix the function name with the module name
Import the module and abbreviate:
import math as m
answer = m.sqrt(3) # prefix the function name with the module abbreviation
Example - Import a single function:
from math import sqrt
answer = sqrt(2)
print(answer)
Example - Import the entire module:
import math
pi = math.pi # modules can include constants (unchanging variable values)
print(pi)
answer = math.cos(pi)
print(answer)
Example - abbreviate the imported module name
import math as m
answer = m.log10(1000)
print(answer)
Example:
# Import the time module
import time
# Print current local time as a formatted string
# "Local time" may be ambiguous if running in the cloud!
print(time.strftime('%H:%M:%S'))
print("I'm going to go to sleep for 3 seconds!")
# Suspend execution for 3 seconds
time.sleep(3)
print("I'm awake!")
print(time.strftime('%H:%M:%S'))
Note that some functions return a value, as in the first example where the current time is returned, then printed. But some functions do not return any value. Rather, they just do something, as in the second example, which makes the script pause for a certain number of seconds.
Example:
import os
working_directory = os.getcwd()
print(working_directory)
print(os.listdir()) # no argument gets working directory
# print(os.listdir(working_directory + '/Documents'))
In the examples we have used so far, the modules we have wanted to import have been included in the Standard Library, so we have been able to load them using an import
statement. However, sometimes when you try to import a module that you’ve seen in code examples, you will receive an error message saying that the module can’t be found. In that case, the library containing that module isn’t downloaded to your computer and it must be installed. (Note: we will use “package” and “library” interchangeably and ignore their technical differences.)
The libraries that are installed automatically will depend at least partly on how you installed and are using Python. If you are using Jupyter notebooks installed as part of an Anaconda distribution, many of the commonly used modules not included in the Standard Library will be available to you without needing to install them. The same is true with Colab. If you did a stand-alone installation of Jupyter notebooks, you are more likely to need to install additional libraries.
There are two common installation methods. The standard method uses pip
. If you are using Anaconda, it comes with its own package manager, conda
. Both of these applications are used in the console (Command prompte
on Windows or Terminal
on Mac.) Here is an example of how to install a commonly used package: requests
. In the console, enter the following:
pip3 install requests
If it doesn’t work on your computer, then try it again without the “3”:
pip install requests
(Depending on your installation, the “3” may be important if pip
without the “3” installs Python 2 packages.) You will see lines of printout but eventually you should see a prompt again. Once the installation is complete, you should be able to use the library in your Jupyter notebook.
Note: The name of the library to be installed is often, but not always, the name of the module that you will load. For example, the commonly used BeautifulSoup library is installed using
pip install beautifulsoup4
but is typically loaded in code using
from bs4 import BeautifulSoup
where bs4
is the actual module name. Check the documentation for the library to make sure what the name is of the library before installing (for example this for BeautifulSoup).
Particular objects are instances of generic classes.
Methods are associated with particular classes of objects. Any instance of a class can use a method associated with that class.
A method is essentially a function that is linked to a class.
The form of a method is: object.method()
.
Arguments may be passed into a method. A method may produce a return value or it may carry out an action without returning anything.
Some string class methods are: .upper()
, .lower()
, and .title()
.
Example:
# instantiate a string object
my_message = 'Do not yell at me, Steve!'
# apply the .upper() method to the string object
shouting = my_message.upper()
print(shouting)
ee_cummings = my_message.lower()
print(ee_cummings)
my_book = my_message.title()
print(my_book)
When looking at someone else’s code, you can tell whether an object like something.otherthing()
is a function from the something
module or a method of a something
object by looking at the code. If the top of the code has a statement like:
import something
then it is a function imported from the something
module. If the code has a statement somewhere like:
something = something_else
where an object is assigned to a variable named something
, then it is a method of a something
object.
cos()
function from the math module so that you don’t have to specify the module name when you want to use the function. Also import pi
from the math module in the same way. Write a script to calculate the cosine of pi and also the circumference of a circle with a diameter of 3. If you don’t remember how to calculate circumference, Google it.input()
function returns strings, not numbers.time.sleep()
function to use without a prefix. Then make the script wait (sleep) for one second.The following videos cover content that is not required, but you might find them useful.
The datetime module defines several kinds of objects. Two of them are: date
and datetime
.
Date objects can be instantiated by specifying their year, month, and day: datetime.date(2001,9,11)
. They can also be instantiated using the .today()
method: datetime.date.today()
.
Example:
import datetime
# Instantiate two date objects, numeric arguments required.
sep_11 = datetime.date(2001,9,11)
this_day = datetime.date.today() # method sets the date value as today
print(type(sep_11))
# Create various string representations of the date objects
print(sep_11.isoformat()) # use ISO 8601 format
print(sep_11.weekday()) # numeric value; Monday is 0
print(sep_11.strftime('%A')) # '%A' is a string format code for the day
print()
print(this_day.isoformat())
print(this_day.weekday())
print(this_day.strftime('%A'))
DateTime objects can be instantitated using the current UTC (i.e. Greenwich Mean Time) time using the .utcnow()
method: datetime.datetime.utcnow()
.
Example:
import datetime
# Instantiate a dateTime object
# The dateTime will be expressed as Universal Coordinated Time (UTC)
# a.k.a. Greenwich Mean Time (GMT)
right_now = datetime.datetime.utcnow()
print(type(right_now))
# Create string representations of the datetime object
print(right_now.isoformat())
# See the datetime module documentation for the string format codes
print(right_now.strftime('%B %d, %Y %I:%M %p'))
Both date
and datetime
objects are abstract and don’t have any particular representation. They can be represented as strings using several methods. The .isoformat()
method represents them as strings according to the ISO 8601 standard. The .strftime()
method represents them as strings based on user-defined string format codes.
Notice how this differs from the strftime()
function from the time
module. The strftime()
function returns a string object. It does not create an instance of any abstract object. In contrast, abstract date
and datetime
objects are created by the datetime
module. They are not strings, but string representations of them can be created by several methods.
Optional practice (if you want to practice using the datetime and time modules):
dt
. Instantiate now
as a date and as a datetime using the abbreviation, and print the value of now
. You will probably need to look at the examples. If you get stuck, you can watch the video below.time()
funtion (no arguments) from the time (NOT datetime) module gives the number of seconds since the midnight before January 1, 1970. Time how long it takes the user to enter something (or just press the Enter
/return
key) by finding the difference in time from before the input statement and after it. You can turn this into a reaction time tester by having one person click the run button and another person press the Enter
key as soon as they see or hear the first person click run. You can also see how long it takes Python to execute a line of code by just not having an input statement.Next lesson: Lists and dictionaries
Revised 2022-03-18
Questions? Contact us
License: CC BY 4.0.
Credit: "Vanderbilt Libraries Digital Scholarship and Communications - www.library.vanderbilt.edu"