Python Numbers

Last Updated : 28 Jun, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

In Python, “Numbers” is a category that encompasses different types of numeric data. Python supports various types of numbers, including integers, floating-point numbers, and complex numbers. Here’s a brief overview of each:

Python Integer

Python int is the whole number, including negative numbers but not fractions. In Python, there is no limit to how long an integer value can be.

Example 1: Creating int and checking type

Python
num = -8

# print the data type 
print(type(num))

Output:

<class 'int'>

Example 2: Performing arithmetic Operations on int type

Python
a = 5
b = 6

# Addition
c = a + b
print("Addition:",c)

d = 9
e = 6

# Subtraction
f = d - e
print("Subtraction:",f)

g = 8
h = 2

# Division
i = g // h
print("Division:",i)

j = 3
k = 5

# Multiplication
l = j * k
print("Multiplication:",l)

m = 25
n = 5

# Modulus
o = m % n

print("Modulus:",o)

p = 6
q = 2

# Exponent
r = p ** q
print("Exponent:",r)

Output:

Addition: 11
Subtraction: 3
Division: 4
Multiplication: 15
Modulus: 0
Exponent: 36

Python Float

This is a real number with a floating-point representation. It is specified by a decimal point. Optionally, the character e or E followed by a positive or negative integer may be appended to specify scientific notation. . Some examples of numbers that are represented as floats are 0.5 and -7.823457.

They can be created directly by entering a number with a decimal point, or by using operations such as division on integers. Extra zeros present at the number’s end are ignored automatically.

Example 1: Creating float and checking type

Python
num = 3/4

# print the data type
print(type(num))

Output:

<class 'float'>

As we have seen, dividing any two integers produces a float. A float is also produced by running an operation on two floats, or a float and an integer.

Python
num = 6 * 7.0

print(type(num))

Output:

<class 'float'>

Example 2: Performing arithmetic Operations on the float type

Python
a = 5.5
b = 3.2

# Addition
c = a + b
print("Addition:", c)

# Subtraction
c = a-b
print("Subtraction:", c)

# Division
c = a/b
print("Division:", c)

# Multiplication
c = a*b
print("Multiplication:", c)

Output
Addition: 8.7
Subtraction: 2.3
Division: 1.71875
Multiplication: 17.6

Note: The accuracy of a floating-point number is only up to 15 decimal places, the 16th place can be inaccurate.

Python Complex

A complex number is a number that consists of real and imaginary parts. For example, 2 + 3j is a complex number where 2 is the real component, and 3 multiplied by j is an imaginary part.

Example 1: Creating Complex and checking type

Python
num = 6 + 9j

print(type(num))

Output:

<class 'complex'>

Example 2: Performing arithmetic operations on complex type

Python
a = 1 + 5j
b = 2 + 3j

# Addition
c = a + b
print("Addition:",c)

d = 1 + 5j
e = 2 - 3j

# Subtraction
f = d - e
print("Subtraction:",f)


g = 1 + 5j
h = 2 + 3j

# Division
i = g / h
print("Division:",i)


j = 1 + 5j
k = 2 + 3j

# Multiplication
l = j * k
print("Multiplication:",l)

Output:

Addition: (3+8j)
Subtraction: (-1+8j)
Division: (1.307692307692308+0.5384615384615384j)
Multiplication: (-13+13j)

Type Conversion in Python

We can convert one number into the other form by two methods:

Using Arithmetic Operations: 

We can use operations like addition, and subtraction to change the type of number implicitly(automatically), if one of the operands is float. This method is not working for complex numbers.

Example: Type conversion using arithmetic operations

Python
a = 1.6
b = 5

c = a + b

print(c)

Output:

6.6

Using built-in functions

We can also use built-in functions like int(), float() and complex() to convert into different types explicitly.

Example: Type conversion using built-in functions

Python
a = 2
print(float(a))

b = 5.6
print(int(b))

c = '3'
print(type(int(c)))

d = '5.6'
print(type(float(c)))

e = 5
print(complex(e))

f = 6.5
print(complex(f))

Output:

2.0
5
<class 'int'>
<class 'float'>
(5+0j)
(6.5+0j)

When we convert float to int, the decimal part is truncated. 

Note: 

  1. We can’t convert a complex data type number into int data type and float data type numbers.
  2. We can’t apply complex built-in functions on strings.

Decimal Numbers in Python

Arithmetic operations on the floating number can give some unexpected results. 

Example 1: Let’s consider a case where we want to add 1.1 to 2.2. You all must be wondering why the result of this operation should be 3.3 but let’s see the output given by Python.

Python
a = 1.1
b = 2.2
c = a+b

print(c)

Output:

3.3000000000000003

Example 2: You can the result is unexpected. Let’s consider another case where we will subtract 1.2 and 1.0. Again we will expect the result as 0.2, but let’s see the output given by Python.

Python
a = 1.2
b = 1.0
c = a-b

print(c)

Output:

0.19999999999999996

You all must be thinking that something is wrong with Python, but it is not. This has little to do with Python, and much more to do with how the underlying platform handles floating-point numbers. It’s a normal case encountered when handling floating-point numbers internally in a system. It’s a problem caused when the internal representation of floating-point numbers, which uses a fixed number of binary digits to represent a decimal number. It is difficult to represent some decimal numbers in binary, so in many cases, it leads to small roundoff errors. 

In this case, taking 1.2 as an example, the representation of 0.2 in binary is 0.00110011001100110011001100…… and so on. It is difficult to store this infinite decimal number internally. Normally a float object’s value is stored in binary floating-point with a fixed precision (typically 53 bits). So we represent 1.2 internally as,

1.0011001100110011001100110011001100110011001100110011  

Which is exactly equal to :

1.1999999999999999555910790149937383830547332763671875

For such cases, Python’s decimal module comes to the rescue. As stated earlier the floating-point number precision is only up to 15 places but in the decimal number, the precision is user-defined. It performs the operations on the floating-point numbers in the same manner as we learned in school.

Related Article – floor() and ceil() function Python

Let’s see the above two examples and try to solve them using the decimal number.

Example:

Python
import decimal

a = decimal.Decimal('1.1')
b = decimal.Decimal('2.2')

c = a+b
print(c)

Output

3.3

We can use a decimal module for the cases – 

  • When we want to define the required accuracy on our own
  • For financial applications that need precise decimal representations

Note: For more information about decimal numbers in Python and the functions provided by this module, refer to Decimal Functions in Python



Previous Article
Next Article

Similar Reads

Convert Strings to Numbers and Numbers to Strings in Python
In Python, strings or numbers can be converted to a number of strings using various inbuilt functions like str(), int(), float(), etc. Let's see how to use each of them. Example 1: Converting a Python String to an int: C/C++ Code # code # gfg contains string 10 gfg = &quot;10&quot; # using the int(), string is auto converted to int print(int(gfg)+2
2 min read
Python Numbers | choice() function
choice() is an inbuilt function in Python programming language that returns a random item from a list, tuple, or string. Syntax: random.choice(sequence) Parameters: sequence is a mandatory parameter that can be a list, tuple, or string. Returns: The choice() returns a random item. Note:We have to import random to use choice() method. Below is the P
1 min read
Python | Numbers in a list within a given range
Given a list, print the number of numbers in the given range. Examples: Input : [10, 20, 30, 40, 50, 40, 40, 60, 70] range: 40-80 Output : 6 Input : [10, 20, 30, 40, 50, 40, 40, 60, 70] range: 10-40 Output : 4 Multiple Line Approach:Traverse in the list and check for every number. If the number lies in the specified range, then increase the counter
6 min read
Python map function | Count total set bits in all numbers from 1 to n
Given a positive integer n, count the total number of set bits in binary representation of all numbers from 1 to n. Examples: Input: n = 3 Output: 4 Binary representations are 1, 2 and 3 1, 10 and 11 respectively. Total set bits are 1 + 1 + 2 = 4. Input: n = 6 Output: 9 Input: n = 7 Output: 12 Input: n = 8 Output: 13 We have existing solution for t
2 min read
Python Dictionary | Check if binary representations of two numbers are anagram
Given two numbers you are required to check whether they are anagrams of each other or not in binary representation. Examples: Input : a = 8, b = 4 Output : YesBinary representations of bothnumbers have same 0s and 1s.Input : a = 4, b = 5Output : NoCheck if binary representations of two numbersWe have existing solution for this problem please refer
3 min read
Python | Generate random numbers within a given range and store in a list
Given lower and upper limits, Generate random numbers list in Python within a given range, starting from 'start' to 'end', and store them in the list. Here, we will generate any random number in Python using different methods. Examples: Input: num = 10, start = 20, end = 40 Output: [23, 20, 30, 33, 30, 36, 37, 27, 28, 38] Explanation: The output co
5 min read
Replacing strings with numbers in Python for Data Analysis
Sometimes we need to convert string values in a pandas dataframe to a unique integer so that the algorithms can perform better. So we assign unique numeric value to a string value in Pandas DataFrame. Note: Before executing create an example.csv file containing some names and gender Say we have a table containing names and gender column. In gender
3 min read
Python | Print all string combination from given numbers
Given an integer N as input, the task is to print the all the string combination from it in lexicographical order. Examples: Input : 191 Output : aia sa Explanation: The Possible String digit are 1, 9 and 1 --&gt; aia 19 and 1 --&gt; sa Input : 1119 Output : aaai aas aki kai ks Approach: Get the String and find all its combination list in the given
2 min read
Python | Make a list of intervals with sequential numbers
Given a list of sequential numbers, Write a Python program to convert the given list into list of intervals. Examples: Input : [2, 3, 4, 5, 7, 8, 9, 11, 15, 16] Output : [[2, 5], [7, 11], [15, 16]] Input : [1, 2, 3, 6, 7, 8, 9, 10] Output : [[1, 3], [6, 10]] Method #1 : Naive Approach First, we use the brute force approach to Convert list of sequen
3 min read
Extract numbers from a text file and add them using Python
Python too supports file handling and allows users to handle files i.e., to read and write files, along with many other file handling options, to operate on files. Data file handling in Python is done in two types of files: Text file (.txt extension) Binary file (.bin extension) Here we are operating on the .txt file in Python. Through this program
4 min read
How to print Odia Characters and Numbers using Python?
Odia(&#2835;&#2908;&#2879;&#2822;) is an Indo-Aryan language spoken in the Indian state of Odisha. The Odia Script is developed from the Kalinga alphabet, one of the many descendants of the Brahmi script of ancient India. The earliest known example of Odia language, in the Kalinga script, dates from 1051. Vowels: &#2821; &#2822; &#2823; &#2824;
2 min read
Multiply matrices of complex numbers using NumPy in Python
In this article, we will discuss how to multiply two matrices containing complex numbers using NumPy but first, let's know what is a complex number. A Complex Number is any number that can be represented in the form of x+yj where x is the real part and y is the imaginary part. Multiplication of two complex numbers can be done using the below formul
2 min read
Python Numbers, Type Conversion and Mathematics
Prerequisite: Python Language Introduction Python is a general-purpose interpreted, interactive, object-oriented, and high-level programming language. It was created by Guido van Rossum. It is an open-source programming language. Types of numbers in Python There are three numeric types in Python: intfloatcomplex As Python is a Loosely typed languag
4 min read
How to create a list of uniformly spaced numbers using a logarithmic scale with Python?
In this article, we will create a list of uniformly spaced numbers using a logarithmic scale. It means on a log scale difference between two adjacent samples is the same. The goal can be achieved using two different functions from the Python Numpy library. Functions Used:numpy.logspace: This function returns number scaled evenly on logarithmic scal
3 min read
How to remove numbers from string in Python - Pandas?
In this article, let's see how to remove numbers from string in Pandas. Currently, we will be using only the .csv file for demonstration purposes, but the process is the same for other types of files. The function read_csv() is used to read CSV files. Syntax: for the method 'replace()': str.replace(old, new) Here str. replace() will return a string
2 min read
How to read numbers in CSV files in Python?
Prerequisites: Reading and Writing data in CSV, Creating CSV files CSV is a Comma-Separated Values file, which allows plain-text data to be saved in a tabular format. These files are stored in our system with a .csv extension. CSV files differ from other spreadsheet file types (like Microsoft Excel) because we can only have a single sheet in a file
4 min read
How to generate random numbers from a log-normal distribution in Python ?
A continuous probability distribution of a random variable whose logarithm is usually distributed is known as a log-normal (or lognormal) distribution in probability theory. A variable x is said to follow a log-normal distribution if and only if the log(x) follows a normal distribution. The PDF is defined as follows. Where mu is the population mean
3 min read
Replace infinity with large finite numbers and fill NaN for complex input values using NumPy in Python
In this article, we will cover how to fill Nan for complex input values and infinity values with large finite numbers in Python using NumPy. Example: Input: [complex(np.nan,np.inf)] Output: [1000.+1.79769313e+308j] Explanation: Replace Nan with complex values and infinity values with large finite. numpy.nan_to_num method The numpy.nan_to_num method
3 min read
How to clamp floating numbers in Python
Clamping is a method in which we limit a number in a range or in between two given numbers. When we clamped a number then it holds the value between the given range. If our clamped number is lower than the minimum value then it holds the lower value and if our number is higher than the maximum value then it holds the higher value. Python doesn't ha
2 min read
How to Round Numbers in Python?
In this article, we will discuss How to Round Numbers in Python with suitable methods and examples of How to round up in Python. Example: Input: 3.5 Output: 4 Explanation: Nearest whole number. Input: 3.74 Output: 3.7 Explanation: Rounded to one decimal place.Round Up Numbers in PythonRounding a number means making the number simpler by keeping its
9 min read
Complex Numbers in Python | Set 2 (Important Functions and Constants)
Introduction to python complex numbers: Complex Numbers in Python | Set 1 (Introduction) Some more important functions and constants are discussed in this article. Operations on complex numbers : 1. exp() :- This function returns the exponent of the complex number mentioned in its argument. 2. log(x,b) :- This function returns the logarithmic value
4 min read
Complex Numbers in Python | Set 3 (Trigonometric and Hyperbolic Functions)
Some of the Important Complex number functions are discussed in the articles below Complex Numbers in Python | Set 1 (Introduction) Complex Numbers in Python | Set 2 (Important Functions and constants) Trigonometric and Hyperbolic Functions are discussed in this article. Trigonometric Functions 1. sin() : This function returns the sine of the compl
4 min read
Lambda expression in Python to rearrange positive and negative numbers
Given an array of positive and negative numbers, arrange them such that all negative integers appear before all the positive integers in the array. The order of appearance should be maintained. Examples: Input : arr[] = [12, 11, -13, -5, 6, -7, 5, -3, -6] Output : arr[] = [-13, -5, -7, -3, -6, 12, 11, 6, 5]\Input : arr[] = [-12, 11, 0, -5, 6, -7, 5
2 min read
Slicing with Negative Numbers in Python
Slicing is an essential concept in Python, it allows programmers to access parts of sequences such as strings, lists, and tuples. In this article, we will learn how to perform slicing with negative indexing in Python. Indexing in PythonIn the world of programming, indexing starts at 0, and Python also follows 0-indexing what makes Python different
6 min read
Words to Numbers Converter Tool in Python
In this tutorial, we will guide you through the process of building a Word-to Numbers converter using Python. To enhance the user experience, we will employ the Tkinter library to create a simple and intuitive Graphical User Interface (GUI). This tool allows users to effortlessly convert words into numbers by inputting the desired word, clicking a
2 min read
How to format numbers as currency strings in Python
Formatting numbers as currency strings in Python is a common requirement especially in the applications involving financial data. Formatting numbers as currency strings in Python involves presenting numeric values in the standardized currency format typically including the currency symbol, thousands separators and the number of the decimal places.
3 min read
Python | Multiply all numbers in the list
Given a list, print the value obtained after multiplying all numbers in a Python list. Examples: Input : list1 = [1, 2, 3]Output : 6Explanation: 1*2*3=6Input : list1 = [3, 2, 4]Output : 24 Multiply all Numbers in the List in Python There are multiple approaches to performing multiplication within a list. In this context, we will utilize commonly em
8 min read
Find Maximum of two numbers in Python
Given two numbers, write a Python code to find the Maximum of these two numbers. Examples: Input: a = 2, b = 4Output: 4 Input: a = -1, b = -4Output: -1 Find Maximum of two numbers in PythonThis is the naive approach where we will compare two numbers using if-else statement and will print the output accordingly. Example: [GFGTABS] Python # Python pr
3 min read
Random Numbers in Python
Python defines a set of functions that are used to generate or manipulate random numbers through the random module. Functions in the random module rely on a pseudo-random number generator function random(), which generates a random float number between 0.0 and 1.0. These particular type of functions is used in a lot of games, lotteries, or any appl
7 min read
Create three lists of numbers, their squares and cubes using Python
In this article, we are going to create a list of the numbers in a particular range provided in the input, and the other two lists will contain the square and the cube of the list in the given range using Python. Input: Start = 1, End = 10Output:Numbers_list = [1,2,3,4,5,6,7,8,9,10]Squares_list= [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]Cubes_list = [1
4 min read
Practice Tags :