Python supports four predefined numeric data types.
These data types are defined as classes:
int (signed integer)bool (boolean, subtype of int)float (real number)complex (complex number)Example
var1 = 1
print(type(var1))
var2 = True
print(type(var2))
var3 = 12.34
print(type(var3))
var4 = 1.2 + 3.4j
print(type(var4))
There are three ways to form an integer: literal representation, expression that evaluates to an integer, and using the int() function which performs a type conversion.
Example
a = 1 # représentation littérale
b = int(1.2) # function int()
c = a + b # expression
A real floating point number (float) consists of an integer part and a decimal part separated by a period.
There are three ways to form a real number: literal representation, expression that evaluates to a real number, and using the float() function.
Example
a = 1.2 # literal representation
b = float(12) # function float()
c = a + b # expression
Scientific notation
In scientific notation, a real number consists of a mantissa m and an exponent n: mEn or men, with 1 ≤ m < 10 and n is the exponent of 10.
Example
a = 1.2E3
A complex number consists of a real part and an imaginary part.
There are three ways to form a complex number: literal representation, expression that evaluates to a complex number, and using the complex() function.
Example
a = 1.2 + 3.4j # literal representation
b = complex(5.6, 7.8) # function complex()
c = a + b # expression
The complex class defines two attributes named real and imag that return the real part and the imaginary part of an object of the complex class, respectively.
The complex class defines a method named conjugate() that returns the conjugate of an object of the complex class.
Example
a = 1 + 2j
print(a.real)
print(a.imag)
print(a.conjugate())
math ModulePython’s math module defines various mathematical functions: trigonometry, logarithms, probability, statistics, etc.
To use it in a program, we must first import the math module.
Example
import math
print(math.pi)
print(math.cos(math.pi))
print(math.sqrt(2))
print(math.exp(1))
print(math.log10(1000))
print(math.factorial(6))
Note
The complex data type is handled in Python’s cmath module.
The random() function generates a random real number in the range [0.0, 1.0].
This function is defined in the Python random module.
To use it in a program, you must first import the random module.
Example
import random
print(random.random())