Home Lesson-3.1

Lesson-2.4

Library

A library is a collection of functions that share a common theme. This is a loose definition and will become clear when we start working with a library.

calendar

Consider the following problem:

In the year , ​ August will fall on which day of the week?

Python to the rescue:

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! calendar is one among several libraries in Python's standard library. A comprehensive list can be found here. Going back to the code, calendar is the name of the library and import is the keyword used to include this library as a part of the code.

calendar is a collection of functions that are related to calendars. prmonth is one such function. It accepts <year> and <month>, as input and displays the calendar for <month> in the year <year>. If we want to use a function in calendar, we must first import the library. Let us see what happens if skip this step:

It gives the following error:

To access a function defined inside a library, we use the following syntax:

Another way to solve the problem is to use the function weekday:

The output of the above code is 4. Days are mapped to numbers as follows:

DayNumber
Monday0
Tuesday1
Wednesday2
Thursday3
Friday4
Saturday5
Sunday6

 

time

Let us now try to answer this hypothetical question:

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

The output is:

The syntax of the import statement in line-1 looks different. from is a new keyword. The first line of the code is essentially doing the following: from the library called time import the function called ctime. This way of importing functions is useful when we need just one or two functions from a given library:

sleep(x) is a function in time that suspends the execution of the program for x seconds. If we would be using several functions in the library, then it is a bad idea to keep importing each of them individually. In such cases, it is good to fall back on importing the entire library.

 

this

As a fun exercise, consider the following code:

This gives the following output:

These are some nuggets of wisdom from Tim Peters, a "major contributor to the Python programming language" [refer]. Some of the points make immediate sense, such as "readability counts".