Python provides functionality for almost everything one can think of. Taking numbers as an example, we see that the language is overloaded with features to help developers in dealing with numbers.
In this chapter, we shall get to know the basics of numbers in Python — the most common classes of numbers i.e integers and floats; converting between these classes, the behavior of some arithmetic operators; and a lot more.
The concept of an integer is pretty trivial — it's a whole number without any fractional component.
-1856 and so on.
We can create an integer in Python just how we define it normally:
x = 10 y = -3
x holds an integer
y holds another integer
Integers in Python belong to the class
We've already seen an evidence to this when we were inspecting integers in the shell using
type(), back in the Python Data Types chapter. Let's review it.
On integers, the
type() function returns the following:
'int' following the word
class here represents the class to which the value passed to
type() belongs. In this case, the value (which was
10) belongs to the class
What is a class?
A class is basically a template for an object - it defines all the traits of an object belonging to it. The
int class is the template here — it defines everything related to integers in Python. The value
10 is referred to as an instance of this class — it is an object belonging to this class.
As an analogy, think of the books around you. What traits do books have — they have an author, a category, number of pages, book format and so on. All these traits can be defined by the class 'Book'.
Every book that you have would then belong to the class 'Book' — in other words, each book would be an instance of this class.
We'll learn more about classes and instances in the Python Classes chapter.
int() class can also be called, like a function, in order to create an integer from a given value.
When called without an argument,
On the other hand, when called with an argument,
int() tries to coerce the argument into an integer and return it.
For example, let's suppose that you have a string holding the number
10 in it, as
Doing arithmetic with this string would not be possible — one would have to first convert it into a numeric type to be able to perform arithmetic operations on it. And for this, one could use the
int() function if it's desired to convert the string into an integer, as shown below:
num = '10' # convert num into an integer num = int(num) print(num + 5) # 15
As you start programming more often, you'll notice this type of conversion pretty mainstream in your applications.
int() doesn't just accept strings to be converted into integer values — it can do this for other data types as well, such as floats, Booleans, and so on.
Consider the snippet below where we demonstrate this:
Remember one thing! The
int() function would throw an error if the value provided to it couldn't be coerced into an integer.
For example, if we provide
int(), the function would throw an error. This is because
'Hello' doesn't have any sensible conversion into an integer.
Surprisingly, even if the string holds a float, then also would
int() throw an error as shown below:
Consider the example below, where we multiply three large numbers together, to get an even larger number. The result of this expression is also an integer, and capable of being stored in Python and being used in any valid expression.
And guess what — arithmetic with such humungous integers is not slow at all (in most calculations)!
Floating-point numbers, or floats, are numbers that have a fractional part to them, where the fractional part can also be zero.
-100.0003 and so on.
Creating a floating-point number in Python is as easy as creating an integer:
x = 3.01 y = -0.5
x holds the number
y holds the number
All floating-point numbers in Python belong to the class
Python uses the IEEE-754 double precision floating-point format to represent floats. In this format, each float takes exactly 64 bits of memory.
Unlike integers in Python, floating-point numbers have a size limit; thanks to the IEEE-754 floating-point format that imposes this limit.
The maximum value possible is
1.8 x 10308 while the minimum
-1.8 x 10308 is its negation. Going below the minimum or above the maximum value results in a special value known as infinity.
Consider the code below:
x = 2e500 print(x) # inf
The value of
x is not what we've written — but rather it is
inf. The value
inf is a special value that means infinity.
infin detail in the following sections.
When we compute a float that's large than the maximum value capable of being stored in a floating-point number, Python replaces it with the value
Moving on, sometimes a floating point number has a fractional part of
0, such as
-55.0 etc. Such a float is technically an integer, and Python realises this fact by giving a simple way to check such a case.
What is that?
is_integer() method of
float objects, we can check whether a given float is actually an integer or not. If it's an integer,
Consider the following code:
f = 30.1 print(f.is_integer()) f = 30.0 print(f.is_integer())
30.1 is not an integer, and likewise
f.is_integer(), in line 2, returns
False. On the other hand,
30.0 is an integer and likewise
True in line 5.
It's common in mathematics to represent extremely large or extremely small numbers in standard form, also known as scientific form, or scientific notation.
m x 10n
m is called the significand, or the mantissa, and
n is called the order of magnitude of
156.2 would be represented as
1.562 x 102 in standard form. Here
1.562 is the significand and
2 is its order of magnitude.
Representing numbers in this way in Python is possible via the
esymbol denotes the power of
10by which to multiply a given significand with.
Let's see how to use the
e symbol to represent
156.2 in scientific notation, we would write
1.562e2. The number preceding
e is the significand, while the number following it is the order of magnitude (the exponent of
Negative exponents are also possible:
10e-2 simply means
10 x 10-2, which is equal to
Starting from Python 3.3, there is a special division operator denoted using two forward slashes
//. It performs what is known floor division.
Floor division operates just like normal division except for that it floors the result of the division in the end. Flooring the result means that it rounds it to the nearest smallest integer.
Consider the example below:
10 // 4
9 // 5
10 // 4, first
10 / 4 is computed. This returns
2.5. Then, this value is floored to give
2. Similarly, in
9 // 5, first
9 / 5 is computed which returns
1.8. This value is floored to give
As can be seen in the examples above, the result of a floor division is an integer.
Why is there a floor division operator?
There are numerous uses of flooring the result of the division of two numbers in computer science. Many many algorithms rely on this idea, and so the
// operator can be a shortcut to the flooring needs of these algorithms.
Otherwise we would have to take a longer way to floor the result of the normal division of the numbers (done by the
/operator (which performs normal division from Python 3.3 onwards) performs floor division.
Raising a number to the power of another number is a common operation we do all the time in mathematics. It's known as exponentiation.
It's possible to do exponentiation in Python, and almost all programming languages. There are essentially 3 ways to exponentiate in Python:
- Using the
- Using the
We shall cover the first two ways right now.
** exponentiation operator
The exponentiation operator raises its first operand to the power of the second operand. It can be represented as follows:
base ** exponent
The first operand is known as the base, while the second one is known as the exponent.
If either of the operands of the exponentiation operator is a float, the result of the exponentiation will also be a float. If this isn't the case — that is, both the operands are integers — then the result would be an integer.
Let's take a quick example:
2 ** 3
5 ** 5
Using the exponentiation operator, we can also compute the square root of any number using an exponent of
Following we compute the square root of a couple of integers:
16 ** 0.5
100 ** 0.5
In general, we can compute the nth root of a given number by setting the
exponent operand to
1 / n (given that the result turns out to be a real number).
Let's compute the cube root of
8 and the quartic root of
8 ** (1 / 3)
81 ** (1 / 4)
The second way to exponentiate a number is using the global function
pow(), which stands for 'power'.
It raises its first argument to the power of the second argument. The
pow() function operates exactly like the exponentiation operator.
Below we perform the same computations as we did above:
pow(8, 1 / 3)
pow(81, 1 / 4)
What's the difference between
On the first sight, one would think that both the exponentiation operator and the
pow() function are exactly the same thing — and indeed they are. The thing is that, if they are the same, then what's the point of having two ways to accomplish the same thing?
pow() operate similarly only if
pow() is provided two arguments. If an optional third argument is provided to
pow(), then the difference between these two becomes pretty much apparent.
The third argument to
pow() applies the modulo operation over the result of exponentiating the first argument with the second one. And this is done superbly efficiently using theorems from number theory. Overall the operation is known as modular exponentiation.
In general terms,
pow(b, n, m), returns the same result as
b ** n % m (but in the blink of an eye!).
Computing the remainder manually by applying the modulo operator over
b ** n can be highly inefficient when the numbers
n are huge.
So the difference between
pow() is now clear:
pow() can also compute modular exponentiations.
If you ever want to compute the remainder when a huge number
bn is divided by a number
m, you should definitely go for the
pow() function. Otherwise, you should stick with the
** operator to exponentiate numbers, since it's relatively faster than the
** is faster than
pow(), as it involves no function invocation — a concept we shall understand later on in this course.
Following from the IEEE-754 format, that Python uses to represent floats internally, there are two special numbers in the language:
Both these numbers are available on the
math module, by the names
infis used to represent infinity - something beyond calculation.
As we've seen above, creating a float that's larger than the maximum value
≈ 1.8 x 10308 or lesser than the minimum value
≈ -1.8 x 10308 results in
This can be seen as follows:
Both the numbers
1.8e308 are above the maximum value capable of being stored in Python, and so boil down to
nan is another special kind of a number.
nanis used to represent something that's not computable in Python.
Consider the code below:
import math print(math.inf - math.inf)
There is no bound to
inf and so subtracting
inf won't return
0, rather it would return
1 / 0evaluates down to
NaN, but in Python it throws an error.