Numbers in Python
Learn via video course

Introduction
You might have used different numbers like integers and decimal numbers in your daily activities. If you have studied mathematics till high school, you might also have learnt about complex numbers. Let us see how these numbers can be used in a python program.
In python, there are four types of built-in numeric data types namely integer, floating point numbers, double, and complex numbers.
Every number in python is a first class object. It means that every number data type is implemented using a class definition.We can check the data type of a number or class to which a number belongs to using the type() method. For example, whole numbers in python are defined as integers. The data type of the numbers can be verified as follows.
Output:
The first number is an integer so data type is returned as class ‘int’ and second number is decimal number so data type is returned as ‘float’.
Now, we will study each built-in numeric data type one by one.
Integer Data Type in Python
Integer data type in python is used to represent the whole numbers like 0, 1, 2, 3, 4 or negative integers such -1,-2, -3 etc. To define an integer variable, you can simply define a variable and assign a number to it as follows.
Output:
Unlike other programming languages, There is no limit on values of integer data types in python. You can define a number as large as per your wish but it is limited by the capability of your computer. For example, here we have created an integer of 86 digits.
Output:
Python also supports integer data types for other number systems such as binary, octal and hexadecimal number systems.
We can represent a binary number in Python by using a 0b prefix to the number as in 0b1110, hexadecimal numbers using the prefix 0x as in 0x1117, and octal numbers using the prefix 0o as in 0o1117.
Output:
You can observe that the data type of every number is int irrespective of the number system. Each number whether binary, octal, or hexadecimal is an object of int class.
Float Data Type in Python
Float represents floating point numbers in python. Decimal numbers or you can say real numbers are represented in python using double precision floating point numbers. A floating point number can be positive, negative or zero. Just like decimal numbers, floating point numbers also contain one or more digits after a decimal point.
Output:
Float data type in Python has a major disadvantage. In python, float data type is implemented using binary fractions. Due to this, the numbers represented using float data type in python are only an approximation of the actual values. In critical situations, these approximations can cause major faults in softwares.
For example, if we add two numbers 1.2 and 2.2, the answer should be 3.4. But, If we compare the sum to 3.4, it will not be equal due to decimal precision. This can be observed in the following example.
Output:
To avoid these errors, you can perform business critical and scientific calculations using the decimal module that we have discussed later in this article.
Complex Numbers in Python
Python also supports built-in complex number data type. A complex number in python is represented in the format a + i b where a and b are numerical values representing the real and imaginary part of the complex number respectively. We can use any english alphabet in place of i.
Output:
As you can see in above example the data type is returned as ‘complex’.
Another way to define a complex number is by using the complex() function. The real and imaginary parts of the required complex number are passed to the complex() function and it returns a complex number. Real part will be passed as the first argument and the imaginary part will be as second argument, also real part is compulsory and the imaginary part is optional.
Output:
We can access the real and imaginary part of a complex number using its attributes “real” and “imag” respectively as follows.
Output:
We can also find the conjugate of the complex number using the conjugate() method. The conjugate() method returns the complex conjugate of a complex number as follows.
Output:
Till now, we have studied all the built-in data types. Let us look at some of the custom numeric data types in python that have been implemented in the form of modules.
Python Decimal
We have seen that the floating point numbers in python have certain limitations in terms of accuracy and precision. To avoid the errors that may arise due to floating point numbers, we can use the decimal module to perform calculations on decimal numbers. The module can be imported using the import statement as follows.
The decimal numbers can be represented by their exact value with exact precision using the decimal module and thus it avoids any approximation error. We can define a decimal number using the decimal module as follows.
Output:
You have to keep in mind that you must not convert a floating point number to a decimal number. If done, the approximation error is propagated to the decimal value from the floating point number. Thus it will give no benefit in this case. The approximation error can be observed in the following example.
Output:
Python Fractions
In python, Fractions have been implemented explicitly using the fractions module. To use the fraction data type in python, you can import the fractions module using the import statement as follows.
To define a fraction object in python using integers, you can use the Fraction() method of fractions module. It takes two numbers as input. The first input is deemed to be the numerator and the second input is considered to be the denominator. After execution, the Fraction() method returns a fraction object that is numerator/ denominator.
Output:
You can also convert a floating point value to fraction using the Fraction() method as follows.
Output:
We will discuss other methods to define a fraction from string in the next section.
Data Type Conversion in Python
String to Integer Conversion
We can convert a string into an integer using the int() method. The int() method takes the string as input and returns an integer value with base 10.
Output:
Here, the string can contain only the combination of digits from 0 to 9. If any characters other than these digits are present in the string, the int() method will raise ValueError.
Output:
String to Float Conversion
You can convert a string to a floating point number using the float() method. The float() method takes the string as input and returns the floating point value as follows.
Output:
The string given to the float() method must consist of only the decimal digits and a period i.e. decimal point (.) may be present in between them. Presence of any other character or more than one period will cause ValueError as follows.
Output:
String to Decimal Conversion
We can also convert a string to a decimal number using the Decimal() method. The Decimal() method takes the string as input and returns the decimal value as follows.
Output:
The string given to the Decimal() method must consist of only the digits and a period may be present in between them. Presence of any other character or more than one period will cause decimal.InvalidOperation error as follows.
Output:
String to Fraction Conversion
You can convert a string to a fraction using the Fraction() method. The Fraction() method takes the string as input and returns the fraction value.
The input string can be the string representation of an integer, a floating point value or a fraction. The output for these string inputs will be as follows.
Output:
When the input string contains inappropriate characters like alphabets and punctuation marks instead of the fraction representation of a number, the Fraction() method will raise ValueError as follows.
Output:
Integer to Float Conversion
An integer can be converted into a floating point value directly using the float() method. The float() method takes the integer as input argument and returns the floating point value as follows.
Output:
Float to Integer Conversion
We can also convert a floating point value to an integer using the int() method. The int() method takes the floating point number as input and returns an integer after dropping the digits after decimal from the input number.
Output:
Float to Decimal Conversion
Although of no use, we can convert a floating point number to decimal using the Decimal() method of decimal module as follows.
Output:
Decimal to Float Conversion
We can convert the decimal number to the floating point number using the float() method of decimal module as follows.
Output:
Float to Fraction Conversion
We can convert a floating point value to a fraction using the Fraction() method. The Fraction() method takes a floating point value as input and returns the fraction value as follows.
Output:
In the above output, numerator and denominator values are very large. We can restrict the value of the numerator and denominator using the limit_denominator() method. The limit_denominator() method takes the maximum allowed value which you want to set for the denominator and modifies the fraction according to it as follows.
Output:
Fraction to Float Conversion
We can convert the fraction to the floating point number using the float() method as follows.
Output:
Fraction to Decimal Conversion
You cannot convert a fraction to a decimal value. If you try to do it using the Decimal() method, TypeError will occur with a message “TypeError: conversion from Fraction to Decimal is not supported”.
Output:
Decimal to Fraction Conversion
You can convert a decimal to a fraction using the Fraction() method. The Fraction() method takes a decimal value as input and returns the fraction value as follows.
Output:
Python Math Module
The math module in python contains different functions and mathematical constants that are required to perform mathematical operations. You can import the math module using the import statement as follows.
Mathematical Functions in the Math Module
There are various mathematical functions defined in the math module. Some of them are discussed below.
math.ceil()
This function rounds a floating point number to the nearest integer greater than the number.
Output:
When an integer is passed to the function as input, the output remains the same as the input number.
Output:
math.floor()
This function rounds a floating point number to the nearest integer less than the number given as input.
Output:
When an integer is passed to the function as input, the output remains the same as the input number.
Output:
math.exp()
This function takes a number, say x as input and returns ex (exponential of x) .Here e is the Euler’s number having value 2.718282.
Output:
math.factorial()
This function is used to calculate the factorial of a number as follows.
Output:
As we know that factorial of a number is defined only for non negative integers, if we pass a floating point value as input to the factorial() function, It raises ValueError exception with a message “ValueError: factorial() only accepts integral values”.`
Output:
Similarly, when we pass a negative value as input to the factorial function, it raises ValueError exception with a message “ValueError: factorial() not defined for negative values”.
Output:
math.gcd()
The gcd() function is used to calculate the greatest common divisor of two numbers.
Output:
Here, the input arguments must be integers. Otherwise the gcd() function raises TypeError exception with a message “TypeError: 'float' object cannot be interpreted as an integer”.
Output:
math.log()
The log() function is used to calculate the logarithm of a positive number to a specified base. The function takes the number as the first argument which is compulsory argument and the base to which the logarithm has to be calculated as the optional second argument and returns a floating point value as output.
Output:
If there is no input given as base, the function calculates the natural log of the input number (with base e).
Output:
We know that logarithms are not defined for 0 and negative numbers. If these numbers are given as input, the function raises the ValueError exception with the message “ValueError: math domain error”.
Output:
math.log10()
The log10() function is used to calculate the logarithm of a positive number to the base 10. The function takes the number as input argument and returns a floating point value as output.
Output:
Logarithms are not defined for 0 and negative numbers. If these numbers are given as input, the function raises the ValueError exception with the message “ValueError: math domain error”.
Output:
math.log2()
-
The log2() function is used to calculate the logarithm of a positive number to the base.
-
The function takes the number as input argument and returns a floating point value as output.
Output:
Logarithms are not defined for 0 and negative numbers. If these numbers are given as input, the function raises the ValueError exception with the message “ValueError: math domain error”.
Output:
math.sqrt()
The sqrt() function is used to calculate the square root of non negative numbers. The function takes a number as input argument and returns the output as follows.
Output:
Square roots are not defined for negative numbers. If a negative number is passed as input to the sqrt() function, it raises the ValueError exception with the message “ValueError: math domain error”.
Output:
math.pow()
The pow() function is used to calculate power of one number to another. The function takes two input arguments. Suppose that x is the first input argument and y is the second input argument. Then the output result will be a value xy.
Output:
Trigonometric Functions
The math module also offers various trigonometric functions that we can use in our programs. Some of them are discussed below.
math.sin()
This function takes a number as input and returns its sine.
Output:
math.tan()
This function takes a number as input and returns the tangent of the number.
Output:
math.cos()
This function takes a number as input and returns its cosine.
Output:
math.asin()
This function takes a number as input and returns its arc sine.
Output:
math.acos()
This function takes a number as input and returns its arc cosine.
Output:
The inputs to acos() and asin() must lie between -1 and 1. Otherwise, ValueError will occur with a message “ValueError: math domain error”.
math.atan()
This function takes a number as input and returns the arc tangent of the input number.
Output:
Mathematical Constants
Various mathematical constants are also defined in the math module. Following is a table of some of the mathematical constants.
Constant | Value |
---|---|
math.e | Euler’s Number (2.718281828459045) |
math.inf | Positive infinity(inf) |
math.nan | Not a Number(nan) |
math.pi | Pi (3.141592653589793) |
math.tau | Tau (6.283185307179586) |
Random Numbers in Python
If you want to generate random numbers for any use case like OTP generation or many more then you can use the random module in python for generating random numbers. You can import the module using the import statement as follows.
To generate a random floating point number, you can use the random() function in the random module. The random() function generates a random floating point number when executed as shown in the example below.
Output:
To generate a random integer value, you can use the randint() function. The function takes the upper limit and lower limit of values as input arguments and returns a random integer between them as follows.
Output:
Conclusion
In this article, we have discussed built-in number data types, decimals and fractions in python. We also studied some of the functions of the math module and implemented some programs with them.