Library in Python
A library is a collection of functions that share a common theme. This loose definition will become clear when we start working with a library.
Using the calendar Library
Consider the following problem:
Problem
In the year 3000, which day of the week will August 15th fall on?
Solution
Output
When the above code is executed, the output is:
15th of August falls on a Friday. Isn't that lovely? It took just two lines of code!
The calendar library is one among several libraries in Python's standard library. A comprehensive list can be found here.
In the code, calendar is the name of the library and import is the keyword used to include this library as part of the code. The calendar library is a collection of functions that are related to calendars. The prmonth function accepts <year> and <month> as input and displays the calendar for that month in the specified year.
Note
If we skip the import step:
It gives the following error:
To access a function defined inside a library, we use the following syntax:
Alternative Solution
Another way to solve the problem is to use the weekday function:
Output
The output of the above code is 4, which means:
| Day | Number |
|-----------|--------|
| Monday | 0 |
| Tuesday | 1 |
| Wednesday | 2 |
| Thursday | 3 |
| Friday | 4 |
| Saturday | 5 |
| Sunday | 6 |
Using the time Library
Let us now try to answer this hypothetical question:
Problem
You are stranded on an island in the middle of the Indian Ocean. The island has a computing device that has just one application installed in it: a Python interpreter. You wish to know the current date and time.
Solution
Output
The syntax of the import statement in line-1 looks different. The from keyword allows us to import a specific function from a library.
This way of importing functions is useful when we need just one or two functions from a given library:
The sleep(x) function in the time library suspends the execution of the program for x seconds. If we would be using several functions in the library, it is better to import the entire library.
The Zen of Python
As a fun exercise, consider the following code:
Output
This gives the following output:
These are some nuggets of wisdom from Tim Peters, a "major contributor to the Python programming language". Some points make immediate sense, such as "readability counts".