A detailed guide to Numeric datatypes in Python

In this Python article, we will discuss the different numeric data types (i.e. integers, float, and complex numbers) available in python.

We will discuss various operations that can be performed on them along with some easy examples.

1. Different Numeric datatype

In python, we have mainly three types of numbers.

Numbers in python
Numbers in python
  • Integers numbers int class
  • Float numbers float class
  • Complex numbers complex class

Here are some examples of numbers

intlongfloatcomplex
1051924361L0.03.76j
999-0x17933L55.4559.j
-6810134L-71.57.389e-27j
-0580935130669817L-20.-.6558+5J
-0x470-032491178673L-37.67e1005e+29J
0x39-5121895289567L89.2-E523.76e-2j
Examples of different Numeric types in Python

We normally use the decimal numbers or (base 10) number system in our daily lives. But in computer programming, we often have to deal with binary (base 2), hexadecimal (base 16), and octal (base 8) number systems.

Number SystemPrefix in Python
Binary‘0b’ or ‘0B’
Octal‘0o’ or ‘0O’
Hexadecimal‘0x’ or ‘0X’
Binary, hexadecimal and Octal
  • Binary – It is a number with syntax containing 0b and eight digits in the 0 and 1 combination representing the binary numbers.
  • Octal – It is a number with syntax containing 0o as prefix.
  • Hexadecimal – It is a number with syntax containing 0x as prefix.

Lets consider an example to understand how it works.

print(0b11101010)
print(0xFC + 0b11)
print(0o13)
Output
234
255
11

Only in Python 2: There is one more datatype associated with long(long integers). It is used when the size of integers is never-ending or unlimited. We just write the integer value and lowercase or uppercase L at the end of the value.

1.1. Integer(int) datatype in Python

int or Integer numbers are those positive or negative numbers that do not have a decimal or these are the number with no fraction value. int in python is the signed integer.

Example 
1,3,89,999

The number which is lead by zeros in an integer value that is non-zero gives an error and is treated invalid. Example: 000123 is an invalid number.

>>> number = 09456
SyntaxError: leading zeros in decimal integer literals are not permitted; use an 0o prefix for octal integers

Normally, we are taught to write 1000 as 1,000 or 10000 as 10,000. But, we cannot write numbers with delimiter as python does not allow comma as number delimiter instead it allows underscore (_) as a delimiter.

Note: Using a comma(,) will convert it into tuple.

>>> number = 12_34_56_78_90
>>> print(number)
1234567890
>>> number = 9,456
>>> print(number)
(9, 456)

We can also convert any given string or float value to an integer with the help of int() function. We should be careful and sure that the another data type represents a number only.

>>> int('90')
90
>>> int('-15')
-15
>>> int('7.8')
7
>>> int("here it will fail")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'here it will fail'

1.2. Float datatype in Python

float numbers are those positive or negative number which has a decimal.

Example 
1.0, 4.7 ,3.9

Same like int datatype, float can also use delimiter (_) instead of comma.

>>> f = 12_12.245_059
>>> f
1212.225059

Float datatype has maximum size according to the individual system. If it reaches beyond its maximum size then we refer to it as ‘inf’, ‘Inf’, ‘INFINITY’, or ‘infinity’. Float 2e400 may be considered as infinity for most systems.

We can also convert any given string or int value to a float with the help of float() function.

>>> float('4.5')
4.5
>>> float('3')
3.0
>>> float('-9')
-9.0
>>> float('1e4')
10000.0
>>> float('Infinity')
inf

1.3. What is Complex datatype in Python

Complex numbers are represented as a+bj where a denotes or contains the real part and b contains the imaginary part.

Example 
3+4j, 5+0.7j

We must use j or J to represent the imaginary component. If we use another character, then it will throw a syntax error.

However, we do not use complex numbers much in normal day-to-day programming activities.

>>> a = 9 + 4j
>>> a
(9+4j)
>>> a = 9 + 4l
SyntaxError: invalid syntax

2. Type Conversion in Python

Python supports automatic conversion of numbers in any given expression which may contain mixed data types to a specific datatype as it makes it easier for evaluation or processing.

Interestingly, python also supports explicit conversion as there may be a need for the program to change the input from one type to another type.

Some of the explicit commands used in python are:

  • int(n) — It will change the number to an integer.
  • float(n) — It will change the number to float.
  • complex(n) — It will change n to a complex number with n as the real part and zero in the imaginary part.
  • complex(n,m) — It will change the number to a complex number with n as real part and m as imaginary part.
  • long(n)Only in Python2. It will change n to a long integer.

Note: Complex numbers can not be converted to other data types.

>>> int(5.3)
5
>>> int(-7.2)
-7
>>> float(7)
7.0
>>> complex('2+9j')
(2+9j)

3. What is Decimal in Python

Some calculations performed by class float in Python may put us in surprise. If we try to make the sum of 2.2 and 4.4, we all know that the sum should be 6.6, but python may not agree.

if (2.2 + 4.4) == 6.6:
   print("True")
else:
   print("False")
Output
False

So, what is happening here? The reason is that float numbers are converted in computer hardware as binary fractions because computers only understand binary forms (0 & 1). Hence, it is computer hardware’s limitation and not an error.

Let’s take an example. As we know that the fraction 2/3 will give 0.66666… which is infinitely long and never ending so we take the approximate value.

Hence, the decimal fraction 0.1 will be an infinitely long binary fraction of 0.00011001100110011… and our computer will store a finite number of it. Which will be approximate 0.1 but it will never be equal.

We can use the decimal module to overcome such issue. The decimal module has user-settable precision unlike the float numbers that have precision up to 15 decimal places.

import decimal
print(0.2)
print(decimal.Decimal(0.2))
Output
0.2
0.200000000000000011102230246251565404236316680908203125

Now the question arises that why we should not implement Decimal every time? The answer is efficiency. float datatype operations are computed faster than Decimal operations.

We can use Decimal in the following few cases.

  • When we want exact decimal representation like in financial applications.
  • When we are required to manage the precision level.

4. What is Fraction in Python

In python, we have some operations which involve fractions numbers and we can implement them using the fractions module.

As we know, a fraction has an integer numerator and an integer denominator. We use fractions for arithmetic operations on rational numbers. Lets’s see how can we create fraction objects.

import fractions
print(fractions.Fraction(3.5))
print(fractions.Fraction(2,9))
Output
7/2
2/9

As we know about imperfect binary float number, we may get odd outcomes while creating Fraction from float. So we can do in this scenario is that we should use a string fraction as it is also supported by Fraction.

from fractions import Fraction as f
print(f(2.2))
print(f('2.2'))
Output
2476979795053773/1125899906842624
11/5

5. Useful Arithmetic Operators

The following table list arithmetic operators on integer values:

Operator(Name)Specification
+ (Addition)To add two values
– (Subtraction)To subtract right value from left value
* (Multiplication)To multiply two numbers
/ (Division)To divide left value by right value(float result is obtained)
% (Modulus)To Return the remainder of the division of the left value by the right value
** (Exponent)To calculate the value of the left-operand raised to the right-operand.
// (Floor Division)Returns floored integer value of a division
Arithmetic operators
>>> 1 + 1
2
>>> 2 - 1
1
>>> 2 * 1
2
>>> 4 / 2
2.0
>>> 5 % 2
1
>>> 3 ** 2
9
>>> 5 // 2
2

6. Useful Mathematical Functions

Some useful mathematical functions are listed below with their specification.

FunctionSpecification
abs(n)It returns the absolute value of n.
ceil(n)It returns the ceiling of n.
cmp(n,m)It will give -1 if n < m, 0 if n == m, or 1 if n > m.
exp(n)It returns the exponential en.
floor(n)It returns the floor of n.
log(n)It returns the logarithm of n (must: n> 0).
log10(n)It returns the base-10 logarithm of n (must: n> 0).
max(n1, n2, n3…)It returns the largest among all its arguments.
min(n1, n2, n3…)It returns the smallest among all its arguments.
modf(n)It returns the fractional and integer parts of n from a two-item tuple. The integer value is returned as a float.
pow(n,m)It returns the value of n**m.
round(n [,m])It returns the rounded value of n to m digits from the decimal point.
sqrt(x)It returns the square root of n.
Common Mathematical functions Python

7. Useful Random Number Functions

Random numbers are used for games, simulations, testing, security, and privacy applications. Python random module includes the following functions that are commonly used.

Sr.No.Function — Specification
1choice(seq)— Gives any random item from a list, or a tuple, or a string.
2randrange ([begin], end ,[step])— Gives randomly selected elements from the range.
3random()— Gives a random float value n, such that 0<=n<1.
4shuffle(lst)— It shuffles all the items of a list and returns None.
5uniform(n,m)— Gives random float x, such that n<=x<m.
Random number functions in python

8. Useful Trigonometric Functions

Some in-built functions to perform trigonometric calculations are listed below. Let the variable name be ‘n‘. Let’s see each of them. All these functions are part of the math module.

Sr.No.Built-in Function & Specification
1acos(n) It will give the radian value of arc cosine of n.
2asin(n) It will give the radian value of arc sine of n.
3atan(n) It will give the radian value of arc tangent of n.
4atan2(m,n) It will give the radian value of atan(m / n).
5cos(n) It will give the radian value of the cosine of n.
6hypot(n,m) It will give the sqrt(n*n + m*m).
7sin(n) It will give the radian value of the sine of n.
8tan(n) It will give the radian value of the tangent of n.
9degrees(n) It converts angle from radian to degree.
10radians(x) It converts angle from degree to radian.
trigonometric function on numbers

We also have two constant value which is in-built in math module.

  • pi The mathematical constant as 3.14
  • e The mathematical constant 2.72

9. Conclusion

In this article we learned about every detail related to numbers in python along with small examples.

  • Different Number datatypes in python, the int, the float, and the complex
  • How to type convert from one data type to another data type.
  • What is a decimal in python and when to use it?
  • What is a fraction in Python and how to use it?
  • The useful Arithmetic operations, Random operations, Trigonometric operations

Complete code samples are present onย Github project.

An investment in knowledge always pays the best interest. I hope you like the tutorial. Do come back for more because learning paves way for a better understanding

Do not forget to share and Subscribe.

Happy coding!! ๐Ÿ˜Š

Recommended -

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x