Get startedGet started for free

Methods and packages

1. Methods and packages

Two concepts in Python that are important to understand are “methods” and “packages.”

2. Methods are functions attached to variables

In Python, everything is an object, and many objects have “methods,” which are special functions that are attached to the object. You can access these by adding a period, then the method onto an object. For example, I can make a string object lowercase by calling the lower() method on that string. This returns a lowercase version of the string. Like lower(), many methods don’t take any arguments, but perform some operation on the object they are attached to, while others take one or more arguments.

3. The .format() method

Methods can be very useful for transforming data. For example, the format() method replaces any curly braces in a string with whatever arguments were passed into the method. This makes it very easy to print-friendly, readable messages about the results of an analysis. Throughout the course, you’ll learn how to use a number of methods for different data structures in Python.

4. Python packages

The other big difference is “packages.” In MATLAB, any functions that get added to your PATH are available for you to use immediately. But in Python, only the most essential functions are accessible in a standard session. The Python Standard Library is distributed with every Python installation and includes many useful general-purpose packages. Data scientists rely heavily on third-party packages like NumPy, Matplotlib, and pandas for data analysis and visualization. Regardless of whether they are part of the Python Standard Library or a third party package, you have to explicitly import them before you can use them.

5. Packages have to be imported

For example, the Python “math” package has functions that implement common mathematical functions, like sine, cosine, and tangent, and maintain math constants like pi. To have access to these functions, you can import them with "import math." Once imported, you can access the functions a package contains with a period, for example, math.log(). If there is just a specific part of a package that you want to import (say, the function log() from the math package), you can use "from" to import just the thing you want.

6. Package aliasing

Sometimes you want to use a package repeatedly, but the name is long, and you don't want to type it over and over again. For these times, Python also supports assigning the package to an alias name using "as." For example, here I've used the syntax "import package as alias" to import the datetime package from the Python Standard Library and assign it to the variable dt. This shorthand is common for the datetime package & many popular packages have common aliases, as well.

7. Let's explore some useful methods and packages

Let’s get some practice manipulating strings with methods and importing packages.