Python Numbers and built-in Math Functions
In this section, we will be learning about Numbers and various Math functions available in python language. In Numbers, we will see some of the most commonly used math operators that we can use to perform various operations on the numbers in python. Under Math functions section, we will learn about some shortcuts (called functions), which are very helpful in calculating some of the complex mathematical expressions like power, sine/cosine, factorials etc. So, let's begin. We recommend keeping the IDLE open, while reading, so that you can practice and learn simultaneously.
In Python we have 6 basic mathematical operators, they are:
Most of you must be familiar with all of the above operators except for the modulo operator. Don't worry we will explain it. Let's start from the beginning.
As you might have guessed it's just simple addition of numbers. In order to test the operator, just go to IDLE and type a number, then addition sign
+, and then another number to add to the first number. Press Enter. This must look like this.
Example: Taking 8 and 19 as example,
On pressing return(or enter), the answer will appear just below the code line. And this is how the output will be displayed, all the time - just below your code line. As you'll hit the enter key, output will appear in the line below.
Don't stop with this example, try using the addition operator with other numbers. Try number with decimal places, like
4.5 + 5.5 and so on.
Just like addition, subtraction has the same syntax. Just change the operator to
-. Again, pick some random numbers and try.
Example: We took
23.67, which gave the output
Same again! Just change the operator to
*, also known as an asterisk. You do know that it's used for multiplication, right? Go ahead and try it in you IDLE.
Example: Take any two numbers and multiply them using the
* operator, just like we did below.
/ sign this time. And try with random numbers. Caution: If you're a beginner, you might find some difficulty in this one. How? Let's see. Let's take some integer numbers (numbers without decimal) like
2, and divide them.
Very well. Next, try with
2. What do you expect the answer would be? Well, according to proper mathematics the answer should obviously be
7.5, but if you actually try this in IDLE, the answer will turn out to be
7. This happened, because if we perform any mathematical operation on an integers then the answer would be an integer. In our case,
2 both are integers, hence, our answer is
7, as the answer has to be an integer.
You might be wondering if it had to be an integer, why it turned out to be
7 and why not any other integer number. Well, that is because the answer is determined as the closest, smaller integer to the original answer. In our case, the original answer is
7.5, thus the nearest integer to it is 7 and 8, and since we have to pick the smaller one; 7 is picked as the answer. In mathematics, it is also known as
floor function (it's there in Python too).
Now talking about the solution to the above problem, all you have to do is, convert any one of the integers(that you want to divide) into decimal, i.e. write
15.0 instead of 15 and/or
2.0 instead of 2.
This mathematical operator is not usually found in common programming languages. In fact, Python is the only language we know which does have an operator for this. In rest of the languages, they use some pre-defined functions (shortcut as we mentioned before) to calculate this. Getting to the point, just put two asterisks like
** between any two numbers. Example, to calculate
2 to the power
10, you have to write:
With that, we now know about all the commonly used mathematical operators of python. Now you can try to combine multiple operators and use them to form one expression. We will recommend using brackets so that python can understand what you want as the answer, i.e. instead of writing
2-(9.0/2). Remember BODMAS, how a mathematical expression with multiple operators is solved in mathematics.
Modulo operator is denoted by
% percentage sign. If you are familiar with the computer programming world, chances are you already know this function. In case you don't, no need to worry. You know division, right? Then you know what remainder is, correct? This Modulo operator, when used with two operands, returns the remainder as the answer. Here are some quick examples.
12%2 = 0, since 2 perfectly divides 12.
13%2 = 1, since dividing 13 with 2 leaves 1 as remainder.
19%5 = 4, because, again,
19/5 leaves 4 as the remainder.
It is used in pretty much the same way as it has been explained here.
To see all the Math operators covered above, live in action, click on the Live Example button,
Live Example →
And that concludes the numbers section. Let's dive into math's function now.
Math Functions in Python
As you learn more about python, you might decide to create a scientific calculator for a project or anything. For that, along with simple mathematical operations, you will have to evaluate some complex mathematical operations as well, like trigonometric operations, logarithmic operations etc. Forget about the calculator, there can be various situations where you might need these functions. Like a software for civil engineers to calculate various parameters of any structure that they are building, or any aerospace software - where they need various kinds of calculations about satellite trajectory, shuttle trajectory and what not. In a nutshell, the complex mathematical operations are used in various real life programs and softwares, hence you must know about them.
Now in Python, some nice guys have already created code pieces (libraries) for almost every mathematical function. We can use these codes without any hesitation and the plus point is, we won't have to re-write it again. Forget about rewriting, we don't even have to know what the complete code is. We only need a few key information to be able to use these readymade code pieces.
Alright, so unofficially function part had already begun. We'll learn about functions in detail in later chapter, thus we'll keep this one short.
Function can be described as a piece of code that may or may not take some value(s) as input, process it, and then finally may or may not return any value as output.
As you can see in the figure above, here input
x is given to a function
f and it is giving some value
f(x) as the output. Although in general programming world, depending upon the purpose of the function, input and output are completely optional. But for a mathematical function, it's very important to have both.
For example, in the trignometric function
sin(x), there must be some value of
x in order to calculate and return the answer, and that pretty much establish why mathematical functions have both input and output.
In python, there are two types of pre-defined functions.
- Inbuilt functions: These are the functions which doesn't require any other(external) code file (known as, Modules or Library Files). These are a part of the python core and are just built within the Python compiler hence there is no hassle of importing these modules/libraries in our code.
- The second type of functions require some external files(modules) in order to be used. The process of using these external files in our code is called importing. So all we have to do is import the file into our code and use the functions which are already written in that file.
It's time to try some of the functions. Let's begin with power functions.
I know what you might be thinking. We just tried that, didn't we? Well, we did saw something that can calculate power, but it was an operator and this one is an inbuilt function (yes, the first type). So, with that just consider this one as an alternative way to calculate power.
Since this one is an inbuilt function, you don't need to import any other library files (or modules), hence it's pretty easy to implement.
Since power function will be needing two numbers(inputs) to perform the operation, i.e. base and exponent, hence we will have to provide two numbers to the function. Go ahead, open the IDLE and write:
Now let's analyse what we did and what will happen. First, we wrote
pow, which is simply the name of the function that we are trying to call. This will tell the python compiler to look out for an inbuilt function named
pow and discover what it can do. Next, within the brackets we wrote two numbers separated with a comma, i.e.
2. Here the first number 3 is base and the second number 2 is an exponent, and we are trying to calculate 32.
Once the python compiler has ensured that all the syntax (the grammar of programming) is correct, it will look for the implementation of the function
pow and use it to find
32. So as you might have expected, the output would be:
With that, we now know, how a function is called. Especially for math functions, we can generalise it as following:
>>> functionName(input1, optionalInput2, optionalInput3, ...)
The values inside brackets that had been separated by commas, which we mentioned to you as input to functions, are called Arguments. As in
pow(x, y) example given above, 3 and 2 were the arguments. There can be any number of arguments in a function. And as we discussed earlier, for a mathematical function there usually is at least one argument present. Let's see some another inbuilt mathematical functions.
Absolute function, also known as Modulus (not to be confused with Modulo), returns the non-negative value of the argument value. Therefore, absolute value of any non-negative number is the same, while for negative numbers, their positive value is returned.
Example: absolute value of
-3 will be
3, absolute value of
-8.74 will be
8.74 and so on.
-99.99 is a negative number, it's positive counterpart will be the output, i.e.
Now let's try some functions where we have to import some modules(or library files).
Since we know sine is a trigonometric function, hence it accepts only one value as an argument, i.e.
x. Here x should be in radians, so you better not confuse it with a degree. As we mentioned before we won't be able to use this function directly. If you do, you might get an error, something like this, which will say name sin is not defined.
This is because the compiler doesn't know what it is supposed to do when it encounters
sin() function, as we have not defined this function but we are trying to use it. So, in order to use it, we will have to import python's math module which consists the implementation of the
sin() function, which will guide the python compiler to understand what to do when
sin() is called.
What we are about to do is called importing a module and it's most oftenly done to use already available ready-made functions. Importing a module takes just one extra line:
>>> import math
Hit enter, and you're done. Now in order to use the
sin() function, go to a new line and type:
3.14159 is approximately the value of
π hence the answer would be near to zero.
As you can see after
math.sin(3.14159) statement, the answer returned was something like
2.653589335273e-6, it might seem a little messy but it is an equivalent representation of
2.653589335273 × 10^-6, or
Because of approximation in the value of
π, the answer too just got deviated a little bit from 0, but you can see the value is almost zero. And at the same time, you can see how accurate the results are.
Now of course there are several other functions available inside math module, like
floor() (floor function; We mentioned this one in division operator),
exp() (Exponential function),
log() (Logarithmic function),
sqrt() (Square root) and a lot more. You can check out the list, their syntax, number of arguments accepted and everything at Python's official website - Mathematical Functions. Python has a manual on their website where you can see all the functions listed with all the details. This manual is called Documentation.