Python Numbers Guide

Meenakshi Agarwal
By
Meenakshi Agarwal
Hi, I'm Meenakshi Agarwal. I have a Bachelor's degree in Computer Science and a Master's degree in Computer Applications. After spending over a decade in large...
11 Min Read
Python Numbers, Type Conversion, and Mathematics

Python numbers are a group of four data types: plain integer, long integer, floating-point, and complex numbers. They not only support simple arithmetic calculations but can also be used in quantum computation as complex numbers. In this tutorial, we’ll try to explain each of them with examples.

Let’s see what numbers in Python are. Like other types in Python, numbers are also objects. They can store an integer, a real, or a composite number. Python numbers are immutable objects so any change in the value would lead to the creation of a new object. Usually, assigning a numeric value to a variable will also cause the creation of an object.

>>> num = 10 + 5j # The number object got created.
>>> print(num)
(10+5j)
>>> type(num) # The number is of complex type.
<class 'complex'>
>>> id(num) # The initial address of 'num' in memory.
10171888
>>> num = 11 + 6j # The 'num' gets a new value.
>>> print(num)
(11+6j)
>>> type(num) # The 'num' is still of complex type.
<class 'complex'>
>>> id(num) # Change in value caused 'num' to have a new memory address.
10171952
Python Numbers, Type Conversion, and Mathematics
Python Numbers, Type Conversion, and Mathematics

Python Numbers – Types of Numeric Data

Interestingly, Python 2.x had four built-in data types (int, long, float, and complex) to represent numbers. Later Python 3.x removed the long and extended the int type to have unlimited length.

The int type

The int type represents the fundamental integer data type in Python. The plain integer in Python 2.x had the maximum size up to the value of sys.maxint.

While in 3.x, the int type got promoted to have unlimited length and thus eliminated the long.

>>> x = 9
>>> type(x)
<type 'int'>

Also Read: How to generate random numbers in Python

The long type

An integer number with unlimited length. Until the end of Python 3, the integers were allowed to overflow and turned into a long. This behavior changed since 3.0 when the ints replaced the longs.

>>> x = 9999999999
>>> type(x) # In Python 2.x, the type will be long. While in 3.x, it is int irrespective of the size.
<type 'long'>

The float type

The float represents a binary floating point number. Using a float variable in an expression automatically converts the adjoining longs and ints to floats.

>>> x = 9.999
>>> type(x)
<type 'float'>

The complex type

The number of this type has a real and an imaginary part. For example – The expression (n1 + n2j) represents a complex type where both n1 and n2 are the floating-point numbers denoting the real and imaginary parts respectively.

>>> x = 3 + 4j
>>> type(x)
<class 'complex'>
>>> x.real
3.0
>>> x.imag
4.0

Python numbers – Key points

1. The number types are automatically upcast in the following order: Int → Long → Float → Complex

2. While integers in Python 3.x can be of any length, a float can only take up to fifteen decimal places.

3. Usually, we work with numbers based on the decimal (base 10) number system. But sometimes, we may need to use other number systems such as binary (base 2), hexadecimal (base 16), and octal (base 8).

In Python, we can deal with such numbers using the proper prefixes. See the table below.

Number SystemBasePrefix to Use
BinaryBase-20b or 0B
OctalBase-80o or 0O
HexBase-160x or 0X

Below is a simple illustration of different number systems using Python code.

>>> x = 0b101
>>> print(x)
5
>>> type(x)
<type 'int'>
>>> print(0b101 + 5)
10
>>> print(0o123)
83
>>> type(0x10)
<type 'int'>

4. If you want to test the class type of a number in Python, then you should use the isinstance() function. Here is an example.

>>> isinstance(2.2, float)
True

5. If you use mixed data types in an expression, then all operands will start to behave as the most complex type used.

>>> 2 + 3.8
5.8

6. Be careful while dividing integers in Python. In Python 2, the division (/) will return an integer quotient as the output. Whereas, in Python 3, the division (/) returns a float quotient as the output.

# Python 2.x
>>> 7/2
3
# Python 3.x
>>> 7/2
3.5

7. The floor operator (//) returns the integer quotient, and the mod (%) operator gives the remainder. However, you can get both these by using the divmod() function.

>>> divmod(7, 2)
(3, 1)
>>> 7 % 2
1
>>> 7 / 2
3.5
>>> 7 // 2
3

Type conversion (casting) in Python

In Python, it is pretty easy to convert any numeric data type into another. We call this process coercion in Pythonic terms.

Basic operations such as addition, and subtraction coerce the integer to float implicitly (by default) if one of the operands is a float.

>>> 2 + 4.5
6.5

In the above example, the first integer (2) turned into a float (2.0) for addition, and the output is also a floating point number.

However, Python lays out a number of built-in functions such as int(), float(), and complex() to convert between types explicitly. These functions can even convert strings to numbers.

>>> int(3.7)
3
>>> int(-3.4)
-3
>>> float(3)
3.0
>>> complex(4 + 7j)
(4+7j)

Please note that if you are doing a conversion of a float to an integer, then the number will get truncated (i.e., the integer that is close to zero).

Also Read: XOR Operator in Python

External classes to handle Python numbers

As you’ve read above Python’s built-in float class has a limit to control precision up to the fifteen decimal places. However, there are other limitations as well because it entirely depends on the computer implementation of the floating point numbers. For example, see the below decimal point issue.

>>> 1.1 + 3.2
4.300000000000001

To overcome such type of issues, we can use the decimal module in Python.

Python Decimal

The decimal module provides the fixed and floating point arithmetic implementation which is familiar to most people. Unlike the floating point numbers which have precision up to 15 decimal places, the decimal module accepts a user-defined value. It can even preserve significant digits in a no.

import decimal

print(0.28)

print(decimal.Decimal(0.28))

print(decimal.Decimal('5.30'))

Output-

0.28
0.2800000000000000266453525910037569701671600341796875
5.30

Python Fractions

Python packages a module named ‘fractions,’ to handle fractional numbers.

A fraction combines a numerator and a denominator; both are of integer data type. This module enables rational number arithmetic functionality.

Here is a simple example to create and use Python fraction objects.

import fractions

print(fractions.Fraction(2.5))

print(fractions.Fraction(5.2))

print(fractions.Fraction(3,5))

print(fractions.Fraction(1.3))

print(fractions.Fraction('3.7'))

Output-

5/2
5854679515581645/1125899906842624
3/5
5854679515581645/4503599627370496
37/10

Must Read: Operators In Python

Python mathematics

Python exposes a few built-in functions to carry out simple mathematical calculations.

For example – abs(), cmp(), max(), min(), round().

print(round(55.26,1))

print(round(66.36,-1))

Output – 

55.3
70.0

Apart from the above methods, we can also use the math module in Python. It provides the following common functions to use.

FunctionDescription
abs(x)The absolute value of x: the (positive) distance between x and zero.
ceil(x)The ceiling of x: the smallest integer not less than x.
cmp(a, b)-1 if a < b, 0 if a == b, or 1 if a > b
exp(x)The exponential of x: ex
floor(x)The floor of x: the largest integer not greater than x.
log(x)The natural logarithm of x, for x> 0.
log10(x)The natural logarithm of x, for x> 0.
max(x1, x2,…)The base-10 logarithm of x for x> 0.
min(x1, x2,…)The smallest of its arguments: the value closest to negative infinity
modf(x)The fractional and integer parts of x in a two-item tuple. Both parts share the same sign as x. The integer part coerces into a float.
pow(x, y)The value of x**y
round(x [,n])x rounded to n digits from the decimal point.
sqrt(x)The square root of x for x &gt; 0
piThe mathematical constant pi.
eThe mathematical constant e.

Here are some examples of using the ceil() function.

Example-1

import math

x = math.ceil(3.5)
print(x)
print(math.ceil(2 + 4.2))

Output –

4
7

Example-2

from math import ceil
 
x = 9 / 4
y = ceil(x)
print(y)

Output –

3

Quick Summary – Python Numbers

With the help of Python numbers and the math module, you can do any basic to advanced computations in Python. We hope this tutorial will be able to uplift your learning spirits.

Anyways, if you find something new to learn today, then do share it with others. Also, follow us on our social media accounts to see more in-depth tutorials.

Best,

TechBeamers

Share This Article
Leave a Comment

Leave a Reply

Your email address will not be published. Required fields are marked *