This article is participating in Python Theme Month. See the link to the event for more details

Python numbers come in four data types: plain integer, long integer, floating point, and complex. Not only do they support simple arithmetic calculations, they can also be used as complex numbers for quantum calculations. In this tutorial, we’ll try to explain each of them with examples.

Let’s see what numbers are in Python. Like any other type in Python, numbers are objects. They can store integers, real numbers, or compound numbers. Python numbers are immutable objects, so any change in the value results in the creation of a new object. Typically, assigning a numeric value to a variable creates a numeric object.

>>> num = 10 + 5j # Digital object created
>>> print(num)
(10+5j)
>>> print(type(num)) # Numbers are complex types
<class 'complex'> > > >print(id(num)) # 'num'Initial address in memory 2819128990512 >>>num+ 6 = 11j # 'num'Get a new value >>>print(num)
(11+6j) > > >type(num) # 'num'is still a complex type <class 'complex'> > > >id(num) # value change causes"num"There is a new memory address 2910237203312Copy the code

Python numbers — The type of numeric data

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

Int (int)

The int type represents the basic integer data type in Python. The maximum size of an ordinary integer in Python 2.x is the value of sys.maxint.

In 3.x, the int type is promoted to have infinite length, eliminating long.

Long (long)

An infinite integer. Until Python 2.x ends, integers are allowed to overflow and become longs. This behavior has changed since 3.0, where long integers were replaced by integers.

Float (floating point)

Floating point numbers represent binary floating point numbers. Using floating point variables in an expression automatically converts adjacent longs and ints to floating point numbers.

>>> x = 9.999 
>>> type(x) 
<type 'float'>
Copy the code

Complex type

This type of number has real and imaginary parts. For example — the expression (n1 + n2j) represents a complex number type, where n1 and n2 are both floating point numbers representing the real and imaginary parts, respectively.

>>> x = 3 + 4j 
>>> type(x) 
<class 'complex'> > > >x.real3.0 > > >x.imag 
4.0
Copy the code

Python numbers — key

A. Numeric types are automatically upconverted in the following order. Int → Long → Float → Complex B. While integers in Python 3.x can be of any length, floating-point numbers are accurate only to 15 decimal places. C. Normally, we use numbers based on a decimal (base 10) number system. Sometimes, however, we may need to use other number systems, such as binary (base 2), hexadecimal (base 16), and octal (base 8). \

In Python, we can handle these numbers with appropriate prefixes. See below.

Into the system Base The prefix to use
binary Base-2 ‘0 b’ or ‘0 b’
octal Base-8 ‘0 o’ or ‘0 o’
hexadecimal Base-16 ‘0 x’ or ‘0 x’
>>> x = 0b101
>>> print(x)
5
>>> type(x)
<type 'int'>
>>> print(0b101 + 5)
10
>>> print(0o123)
83
>>> type(0x10)
<type 'int'>
Copy the code

D. If you want to test the class type of numbers in Python, you should use the isinstance() function.

isinstance(object.class)
Copy the code

This is the sample

>>> isinstance(2.2.float)
True
Copy the code

E. If mixed data types are used in an expression, all operands are changed to the most complex type used.

>>> 2 + 3.8
5.8
Copy the code

F. Be careful when dividing integers in Python. In Python 2.x, division (/) returns an integer quotient as output.

>>> 7/2 
3
Copy the code

In Python 3.x, division (/) returns a floating-point quotient as output.

>>> 7/2 
3.5
Copy the code

G. The base operator (//) returns the integer quotient, and the modular operator (%) gives the remainder. However, you can get both by using the divmod() function.

>>> divmod(7.2) 
(3.1) 
>>> 7 % 2 
1 
>>> 7 / 2 
3.5 
>>> 7 // 2 
3
Copy the code

Casting (casting) in Python

In Python, it’s very easy to convert any numeric data type to another. We refer to this process as a cast in Pythonic terms.

If one of the operands is a floating point number, the basic operations (such as addition, subtraction) force the integer to be implicitly (by default) floating point.

>>> 2 + 4.5 
6.5
Copy the code

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

Python, however, says no. Built-in functions such as int(), float(), and complex() to explicitly convert between types. 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)
Copy the code

Note that if you convert a floating point number to an integer, the number is truncated (that is, an integer close to zero).

An external class that handles Python numbers

As you’ve read above, Python’s built-in floating-point classes have a limitation that controls precision up to 15 decimal places. However, there are other limitations because it depends entirely on the computer implementation of floating point numbers. For example, see the decimal point problem below.

>>> 1.1 + 3.2 
4.300000000000001
Copy the code

To overcome this problem, we can use the decimal module in Python.

Python is a decimal

The decimal module provides fixed-point and floating-point implementations that most people are familiar with. Unlike floating point numbers with precision up to 15 decimal places, the Decimal module accepts user-defined values. It can even keep the significant digits in the number.

import decimal

print(0.28)

print(decimal.Decimal(0.28))

print(decimal.Decimal('5.30'))
Copy the code

The output –

0.28 
0.2800000000000000266453525910037569701671600341796875 
5.30
Copy the code

Python scores

Python packs a module called “fractions” to handle fractions.

A fraction consists of a numerator and a denominator; Both are integer data types. This module enables rational number arithmetic.

Here is a simple example of creating and using an object of type score.

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'))
Copy the code

The output –

5/2 
5854679515581645/1125899906842624 
3/5 
5854679515581645/4503599627370496 
37/10
Copy the code

Python mathematical

Python exposes several built-in functions to perform simple mathematical calculations.

For example, – abs(), CMP (), Max (), min(), round().

print(round(55.26.1))

print(round(66.36, -1))
Copy the code

The output –

55.3 
70.0
Copy the code

In addition to the above methods, we can also use the Math module in Python. It provides the following common functions.

function describe
abs(x) Absolute value of x: the (positive) distance between x and zero.
ceil(x) Upper limit of x: the smallest integer not less than x
cmp(a, b) Minus 1 if a < b, 0 if a == b, or 1 if a > b
exp(x) The exponent of X: ex
floor(x) Lower limit of x: the maximum integer not greater than x
log(x) The natural log of x, for x greater than 0
log10(x) Log base 10 of x greater than 0.
Max (x1, x2,…). Maximum parameter: the value closest to positive infinity
Min (x1, x2,…). Its smallest parameter: the value closest to negative infinity
modf(x) The fractional and integer parts of x in a binomial tuple. Both parts share the same sign as x. The integer part is cast to float.
pow(x, y) x**yThe value of the
round(x [,n]) X is rounded from the decimal point to n places.
sqrt(x) Square root of x greater than 0
pi The mathematical constant π.
e The 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))
Copy the code

The output –

4
7
Copy the code

Example 2

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

The output –

3
Copy the code

Quick summary — Python numbers

With the Python numbers and Math modules, you can do anything from basic to advanced calculations in Python. We hope this tutorial has been helpful to you, and the bloggers are still learning, so if there are any mistakes, please correct them. If you enjoyed this article and are interested in seeing more of it, you can check it out here (Github/Gitee). This is a summary of all my original works and source code. Follow me for more information.

More on this at 🧵

Recommended articles of the past:

  • 20 Python Tips Everyone must Know | Python Theme month
  • 100 Basic Python Interview Questions Part 1 (1-20) | Python topic month
  • 100 Basic Python Interview Questions Part 2 (21-40) | Python topic month
  • 100 Basic Python Interview Questions Part 3 (41-60) | Python topic month
  • 100 Basic Python Interview Questions Part 4 (61-80) | Python topic month
  • 100 Basic Python Interview Questions Part 5 (81-100) | Python topic month

If you do learn something new from this post, like it, bookmark it and share it with your friends. 🤗 Finally, don’t forget ❤ or 📑 for support