Mastering the basic data types for numbers is a must when you learn any programming language. Let’s dive into how Python numbers work and the basic arithmetic and mathematics you should know.
Numeric Types In Python
Python comes with support for three numeric data types:
- integers
- floating-point numbers
- complex numbers
In addition to operators and functions, you can create numeric values through numeric literals.
Those with exponent signs or decimal points represent floating-point numbers. To create a complex number, combine a real part (a numeric literal) and an imaginary part (another numeric literal with ‘j’ or ‘J’ appended to it).
Constructors like int(), float(), and complex() can also be used to create numbers.
Integers
Unlike many other languages, such as C, there is only one data type for all integers in Python. They are presented by the int class and have unlimited precision. You don’t have to worry about their size or sign.
The int() function converts strings or floating-point numbers to integers:
>>> int("45")
45
>>> int(4.5)
4
>>> int(-4.5)
-4
You can apply common algebra operations like add, subtract, multiply, and divide.
>>> a = 9
>>> b = 3
>>> a + b
12
>>> a - b
6
>>> a * b
27
>>> a / b
3.0
>>> 7 / 3
2.3333333333333335
Remember that in Python 3, the slash operator (/) specifies float division, meaning the result will be a float, not int, no matter whether the value of the remainder.
>>> type(6 / 3)
<class 'float'>
>>> type(7 / 3)
<class 'float'>
To carry out integer division, use the double-slash operator (//). It returns the floored quotient of the division (the largest integer that is smaller than the true quotient):
>>> 7 // 3
2
>>> type(7 // 3)
<class 'int'>
The module operator (%) returns the remainder of dividing two integers:
>>> 7 % 3
1
To get both the quotient and remainder of an integer division operation, use the divmod() function. It returns a tuple containing two integers:
>>> divmod(7, 3)
(2, 1)
Python supports common operator precedence, so you can write compound expressions without having to use parentheses to explicitly specify the order of operations.
>>> 1 + 5 * 2
11
>>> 1 + (5 * 2)
11
You can use underscores to mark large integers. They help group digits and make the number more readable without affecting its value. Python ignores those characters when storing and printing the number:
>>> distance = 1_000_000_000
>>> print(distance)
1000000000
>>> distance - 1000
999999000
Floating-point Numbers
Most Python implementations (including the default CPython) use C’s double to represent values of the float class. For this reason, the precision of floating-point numbers depends on the system you are running Python on.
You can obtain more information about the representation (such as the maximum positive finite value) of your installation’s float via sys.float_info.
Use the float() constructor to convert a string or a number of other types to a float. The string argument can have a decimal number, a sign, and whitespaces.
>>> float("3.14")
3.14
>>> float(78)
78.0
>>> float()
0.0
When you give float() a float or int, it will return a float that has the same value within the precision of your Python installation.
Note: follow this guide to learn how to check if a float is a whole number.
While Python’s float supports all arithmetic operations involving int, it has some limitations on precision. Your system uses a finite number of bits to represent float numbers, and this can lead to a loss of precision.
>>> 2.11 - 0.11
1.9999999999999998
>>> 1 + 0.0000000000000000000001
1.0
You should be aware of these errors when working with floating-point numbers in Python. The following expression evaluates to false while most might expect otherwise:
>>> (2.11 - 0.11) == 0.02
False
To avoid those problems, check out the built-in decimal module. It is designed to make high-precision float calculations. The module takes into consideration the way humans understand and calculate those numbers.
The support for rational numbers is provided by the fractions module. It offers the Fraction class, which can be constructed from a numerator and a denominator:
>>> from fractions import Fraction
>>> a = Fraction(1, 3)
>>> print(a)
1/3
>>> type(a)
<class 'fractions.Fraction'>
Arithmetic operations can be used with these Fractions instances:
>>> b = Fraction(2, 3)
>>> a + b
Fraction(1, 1)
Complex Numbers
You can enter a complex number by denoting the imaginary portion with ‘j’:
>>> a = 3 + 4j
>>> type(a)
<class 'complex'>
The complex() constructor can also create a complex number value by providing the real and imaginary parts or converting them from a string or number.
>>> complex(3, 4)
(3+4j)
>>> complex("3+4j")
(3+4j)
Note: you must remove white space surrounding the + or / operator. Otherwise, complex() will raise the ValueError exception.
>>> complex("3 + 4j")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: complex() arg is a malformed string
To extract the real and imaginary part of a complex number, get its attributes “real” and “imag”. Both of them are returned as floating-point numbers.
>>> a = complex(3, 4)
>>> a.real
3.0
>>> a.imag
4.0
Use the conjugate() method to get the conjugate of a complex number:
>>> b = a.conjugate()
>>> b
(3-4j)
Other Mathematical Operations
Exponents are supported with double-multiplication symbols:
>>> 2 ** 4
16
The abs() function returns the absolute value of a number (or any object that has __abs__(). When applied to a complex number, it returns the magnitude:
>>> abs(4.5)
4.5
>>> abs(-8.4)
8.4
>>> abs(4-6j)
7.211102550927978
Python performs implicit type conversion in the case of mixed arithmetic expressions. When given two operands with different numeric types, it automatically converts the “narrower” type to the “wider” one. For example, int values will be converted to float if the other operand is a float.
There are many built-in modules providing additional functions for mathematical operations.
The random module can help you generate pseudo-random numbers with different distributions. In particular, the randint() function returns a random integer within a range defined by you:
>>> import random
>>> random.randint(0, 10)
9
>>> random.randint(0, 10)
10
>>> random.randint(0, 10)
4
The math module, on the other hand, comes with mathematical functions you can find in C. Use it when you want to find the square root of a number or the sine of an angle:
>>> import math
>>> math.sqrt(9)
3.0
>>> math.sin(math.radians(90))
1.0
Tutorials about Python Numbers
Some articles related to Python Numbers that you may be interested in:
- Round a float to 2 decimals in python
- Round a number up to the nearest integer in python
- Check if a number is divisible by another number in Python
- Force division to return a floating-point number in Python
- Get the length of an Integer in Python
- Round a float DOWN to the nearest Integer in Python
- Check if a string contains a number in Python
- Check if a float is a whole number in Python
- Check if a number is an int or float in Python
- Check if a string can be converted to a float in Python
- Convert NoneType to an Integer in Python
- Divide each element in a list by a number in Python
- Split an integer into digits in Python
- How to calculate percentage in Python
- Make division by Zero return Zero in Python
- How to remove the division decimal in Python
- Split a number into integer and decimal parts in Python
- Add zeros to a float after the decimal in Python
- Round a Number to the nearest 10 in Python
- Sum the integers from 1 to n in Python
- The equivalent of sum() for multiplication in Python
- Round a number to the nearest 5 in Python
- What does for i in range len mean in Python?
- Sum a list of float numbers in Python
- Calculate sum using a list comprehension in Python
- Add leading zeros to a number in Python
- Get number without decimal places in Python
- Check if a string is an Integer or a Float in Python
- Round a float to the nearest 0.5 in Python
- Round a number to the nearest 1000 in Python
- Round a number to the nearest 100 in Python
- Print a float to 2 decimal places in Python
- Print integer values in Python
- How to take float user input in Python
- Check if user input is an Integer in Python
- Using f-strings to format floats to N digits after decimal in Python
- Sum the digits in a string in Python
Summary
Python makes it simple for programmers by putting numeric values into only three distinct data types. There are also other classes on top of them to provide other numeric and mathematical capabilities.
My name is Robert. I have a degree in information technology and two years of expertise in software development. I’ve come to offer my understanding on programming languages. I hope you find my articles interesting.
Job: Developer
Name of the university: HUST
Major: IT
Programming Languages: Java, C#, C, Javascript, R, Typescript, ReactJs, Laravel, SQL, Python