Python’s math.log10() function returns the base-10 logarithm of a number. The syntax for this function is relatively straightforward: it takes one argument which is the number whose logarithm you are trying to compute.

For instance, the log10 of 100 is 2 because 10 squared is 100. Similarly, the log10 of 1000 is 3 because 10 cubed is 1000. Recall that you can only compute logarithms of positive numbers greater than 0; if you try to use it with a negative number, then you will get an error message.

Let us write a simple program to do exponentiation and then logarithms immediately after:

In this program, the loop index goes from 1 to 10 (1 less than the second argument of the range operator, which is 11). Inside the loop, we are first computing 10 raised to the power of the index. Then we are computing the log10 of that answer (which should give us back the original number). The output is:

as expected. Note that the logarithms are in floating point notation even though we began with integers.

One important way to understand logarithms is to see how they are distributed. Let us try to find logarithms (to the base 10) of numbers from 1 to 10. It is clear that the logarithm of 1 is zero (because anything to the power of zero is 1). It is also clear that the logarithm of 10 is 1. But what happens in between? How are the logarithms distributed? Here is a program to explore this space:

The output is:

As can be seen the output starts from 0 and grows to 1 but notice the big jump from 0 to 0.3, followed by progressively smaller jumps, till we reach 10.

Let us explore the space of numbers from 10 to 100 similarly:

Note that in the above program we have updated the arguments of the range() operator to start from 10 and go till 100 (one less than 101) but in steps of 10. The output is actually very similar to what we saw earlier:

We see a big jump from 1 to 1.3 and then smaller jumps till we reach 2.

Thus the moral of the story is that logarithms (to any base) reduce the variation you see in your original quantity of interest and compress it into a smaller range.

In conclusion, the math.log10() function offers a simple yet powerful way to calculate base-10 logarithms within your Python programs.

Interested in more things Python? Checkout our post on Python queues. Also see our blogpost on Python's enumerate() capability. Also if you like Python+math content, see our blogpost on Magic Squares. Finally, master the Python print function!

Kodeclik is an online coding academy for kids and teens to learn real world programming. Kids are introduced to coding in a fun and exciting way and are challeged to higher levels with engaging, high quality content.