Computer ScienceChapter 3: Programming Fundamentals (Python)
3.5 Libraries
A library
Explanation level
Introduction
When writing programs, you often need to perform common tasks like working with dates, doing mathematical calculations, or generating random numbers. Instead of writing code for these tasks from scratch every time, Python provides libraries — collections of pre-written, tested code that you can use directly in your programs.
Definition
A library is a set of code which is meant for a particular task, made more proficient.
In simple words, a library is a collection of pre-written code that you can use in your own programs to save time and effort.
Main Idea
We can produce results with just one line of code via using a library, rather than writing our own tens of lines of code.
For example, the Turtle library is already available in Python, which provides already written and tested functions that we can use. We simply have to import the library and use from the available functions, with the right set of arguments.
For any additional library, it can be downloaded and imported similarly.
Core Concept
Libraries work on the principle of reusability. Instead of writing everything from scratch:
- Find a library that already does what you need.
- Import it into your program.
- Use its functions.
This saves time, reduces errors, and makes your code shorter and cleaner.
Detailed Explanation
Why Use Libraries?
Libraries are useful because:
- Save time: You don't have to write common code from scratch.
- Reduce errors: Library code is already tested and debugged.
- Improve quality: Libraries are often written by experts.
- Keep code short: You can do complex tasks with just one or two lines.
- Focus on your problem: You can focus on the unique parts of your program.
The Turtle Library Example
As discussed earlier, the Turtle library is already available in Python. It provides already written and tested functions that we can use.
Without a library: To draw a circle, you would need to write code that calculates points on a circle, moves a pen to each point, and draws lines between them. This would take many lines of code.
With Turtle library: ```python import turtle turtle.circle(50) ```
Just two lines of code draw a circle with radius 50 pixels.
The Datetime Library Example
By default, date is not the type of data supported by Python. But the `datetime` library can be downloaded and imported. This way, date and time in different formats can be accommodated.
Example — Display Current Date and Time:
```python import datetime x = datetime.datetime.now() print(x) ```
Output: ``` 2023-09-13 11:31:46.409063 ```
This shows the current date and time, including year, month, day, hour, minute, second, and microsecond.
Example — Display Only the Month:
```python import datetime x = datetime.datetime.now() print(x.strftime("%B")) ```
Output: ``` September ```
Example — Display Year and Day:
```python import datetime x = datetime.datetime.now() print(x.year) print(x.strftime("%A")) ```
Output: ``` 2023 Wednesday ```
The strftime() Function
The `strftime()` function is used to format dates and times according to the argument you provide. It takes the datetime object and treats it as a string, then extracts the particular output based on the argument.
Common strftime() Arguments:
| Argument | Description | Example |
|---|---|---|
| `%A` | Weekday, full version | Friday |
| `%B` | Month name, full version | August |
| `%C` | Century | 19 |
| `%d` | Day of month (01-31) | 21 |
| `%H` | Hour (00-23) | 18 |
| `%I` | Hour (00-12) | 03 |
| `%S` | Second (00-59) | 48 |
| `%Y` | Year, full version | 2023 |
Package Managers
Rather than manually installing a package and tracing for missing dependencies by going through all the required files one by one and later install them as well, package managers are quite useful.
Pip is a package manager for installing Python packages. It is simple to use and assures that all dependencies of the said package are also installed.
Example — Installing a Package:
To install the `datetime` package, simply type in the command prompt:
``` pip install datetime ```
- Download the package
- Download any dependencies it needs
- Install everything in the correct location
- Make the package available for import
Note: The `datetime` library comes with Python by default, so you don't actually need to install it. But the same command works for other libraries that are not built-in.
Built-in vs External Libraries
| Type | Description | Example |
|---|---|---|
| Built-in libraries | Come with Python, no installation needed | turtle, datetime, math, random |
| External libraries | Need to be installed with pip | numpy, pandas, matplotlib |
Built-in libraries are always available — you just need to import them.
External libraries must be installed first using `pip install library_name`.
How to Import a Library
There are several ways to import a library:
Method 1: Import the whole library ```python import datetime x = datetime.datetime.now() ```
Method 2: Import with a shorter alias ```python import datetime as dt x = dt.datetime.now() ```
Method 3: Import specific functions ```python from datetime import datetime x = datetime.now() ```
Method 4: Import everything (not recommended) ```python from datetime import * x = datetime.now() ```
The most common and recommended methods are Method 1 and Method 2.
Intermediate Level
The Datetime Library — Detailed Examples
Example 1 — Current Date and Time:
```python import datetime x = datetime.datetime.now() print(x) ```
Output: ``` 2023-09-13 11:31:46.409063 ```
- `datetime.datetime.now()` returns the current date and time
- The output shows: year-month-day hour:minute:second.microsecond
Example 2 — Month Only:
```python import datetime x = datetime.datetime.now() print(x.strftime("%B")) ```
Output: ``` September ```
Explanation: - `strftime("%B")` formats the datetime object to show only the full month name
Example 3 — Year and Day:
```python import datetime x = datetime.datetime.now() print(x.year) print(x.strftime("%A")) ```
Output: ``` 2023 Wednesday ```
- `x.year` directly accesses the year attribute
- `strftime("%A")` formats the datetime object to show the full weekday name
The strftime() Function — Common Arguments
The `strftime()` function takes a format string and returns a formatted date/time string. The most common arguments are listed in Table 3.1 of the textbook:
| Argument | Description | Example |
|---|---|---|
| `%A` | Weekday, full version | Friday |
| `%B` | Month name, full version | August |
| `%C` | Century | 19 |
| `%d` | Day of month 01-31 | 21 |
| `%H` | Hour 00-23 | 18 |
| `%I` | Hour 00-12 | 03 |
| `%S` | Second 00-59 | 48 |
| `%Y` | Year, full version | 2023 |
Pip — The Python Package Manager
Pip is the standard package manager for Python. It is used to install, update, and remove Python packages.
Common Pip Commands:
| Command | Purpose |
|---|---|
| `pip install package_name` | Install a package |
| `pip uninstall package_name` | Remove a package |
| `pip list` | List installed packages |
| `pip show package_name` | Show information about a package |
| `pip install --upgrade package_name` | Upgrade a package |
How Pip Works:
- You type `pip install package_name`
- Pip connects to the Python Package Index (PyPI)
- It downloads the package and all its dependencies
- It installs everything in the correct location
- The package is now available for import in your programs
Example — Installing a Package:
``` >pip install datetime ```
This command installs the `datetime` package (though it is built-in, so this is just an example).
Dependencies
A dependency is another package that a library needs in order to work.
- Library A needs Library B to work
- Library B needs Library C to work
If you install Library A manually, you would also need to install B and C.
- You type `pip install A`
- Pip sees that A needs B and C
- Pip installs A, B, and C automatically
This is one of the main advantages of using a package manager.
Formula / Mathematical Form
Not applicable for this topic.
Solved Example
Not applicable for this topic.
Important Points
- - A library is a set of code meant for a particular task, made more proficient.
- - Libraries save time and effort by providing pre-written, tested code.
- - The Turtle library is built-in to Python.
- - The `datetime` library can be downloaded and imported to work with dates and times.
- - The `strftime()` function formats dates and times according to the argument provided.
- - Pip is a package manager for installing Python packages.
- - Pip automatically installs all dependencies of a package.
- - Built-in libraries come with Python; external libraries need to be installed.
- - Common libraries include turtle, datetime, math, random, numpy, pandas.
- - Import a library using `import library_name`.
Remember
- - Library = Set of pre-written, tested code.
- - Turtle = Built-in library for graphics.
- - Datetime = Library for working with dates and times.
- - strftime() = Formats dates and times.
- - Pip = Python package manager.
- - pip install package_name = Installs a package.
- - Built-in libraries = Come with Python.
- - External libraries = Need to be installed with pip.
- - Dependencies = Other packages a library needs.
- - Import = Bring a library into your program.
Common Mistakes
- - Confusing libraries with modules: A module is a single file; a library is a collection of modules and packages.
- - Forgetting to import a library: You must import a library before using its functions.
- - Thinking all libraries are built-in: Only some libraries come with Python; others need to be installed.
- - Not using pip correctly: The command is `pip install package_name`, not just `install package_name`.
- - Ignoring dependencies: If a library needs other packages, pip installs them automatically — but you should be aware of them.
- - Using outdated libraries: Always check for the latest version.
- - Not reading documentation: Each library has its own functions and usage — read the documentation to use it correctly.
- - Thinking you need to install built-in libraries: Built-in libraries like `turtle` and `datetime` are always available — just import them.
Quick Revision
A library is a set of code which is meant for a particular task, made more proficient. We can produce results with just one line of code via using a library, rather than writing our own tens of lines of code.
For example, the Turtle library is already available in Python, which provides already written and tested functions that we can use. We simply have to import the library and use from the available functions, with the right set of arguments.
For any additional library, it can be downloaded and imported similarly. By default, date is not the type of data supported by Python, but the datetime library can be downloaded and imported. This way, date and time in different formats can be accommodated.
Rather than manually installing a package and tracing for missing dependencies, package managers are quite useful. Pip is a package manager for installing Python packages which is simple to use and assures that all dependencies of the said package are also installed.
- Example — Install datetime package:
- ```
- pip install datetime
- ```
The `strftime()` function formats dates and times according to the argument provided. Common arguments include `%A` (weekday), `%B` (month), `%d` (day), `%Y` (year), `%H` (hour), `%S` (second).
60-Second Revision
- Library = Set of pre-written, tested code.
- Turtle = Built-in graphics library.
- Datetime = Library for dates and times.
- strftime() = Formats dates/times (`%A`, `%B`, `%d`, `%Y`, etc.).
- Pip = Python package manager.
- pip install package_name = Installs a package and its dependencies.
- Built-in libraries = Come with Python (turtle, datetime, math, random).
- External libraries = Need to be installed (numpy, pandas, matplotlib).
- **Import** = 0 to use a library.
- Warning: Always import a library before using its functions.
Did you understand this topic?
Your answer is saved with your learning record. It does not mark the topic as mastered.
Quick revision
Revision Zone
Review the key facts, formulas and checks before you move on.3.5 Libraries
Sticky Notes · Quick Revision
Key Point 1
- Library = Set of pre-written, tested code.
Key Point 2
- Turtle = Built-in graphics library.
Key Point 3
- Datetime = Date and time library.
Key Point 4
- strftime() = Formats dates.
Key Point 5
- Pip = Package manager for Python.
Key Point 6
- pip install package_name = Install a package.
Key Point 7
- Built-in libraries = Come with Python.
Key Point 8
- External libraries = Need pip install.
Key Point 9
- Dependencies = Other packages needed.
Key Point 10
- Import = Bring library into program.
Same supplied content as this Notes page (shared canonical source).