1.4. Numeric Data Types#
Python supports various data types, which we will introduce as we encounter them. Understanding data types is crucial because each value in Python is associated with a specific data type, and the behavior of values when they are combined is determined by their data types.
To determine the data type of a value, you can use the type()
function.
type(2)
int
type(3.14)
float
1.4.1. Int and Float#
Values such as 4
and -7
have the data type int
(short for integer
). Values like 2.5
and -17.0
belong to the data type float
(short for floating point
). The value 7j
is an instance of the complex
data type.
int
stores whole numbers, whether positive or negative, with unlimited range.float
stores numbers with decimals, both positive and negative.
With respect to numeric data types, you should know some rules:
An expression involving two
int
operands results in anint
:
1 + 2
3
type(1 + 2)
int
An expression involving two
float
operands results in afloat
:
1.0 + 2.0
3.0
type(1.0 + 2.0)
float
When an expression involves an
int
and afloat
as operands, resulting in a mixed data type, Python automatically converts theint
to afloat
. This is why the following two expressions yield the same data type.
17.0 - 10
7.0
type(17.0 - 10)
float
17 - 10.0
7.0
type(17 - 10.0)
float
You can omit
0
after the decimal point, for instance,10.
, but this practice is generally considered poor style.
10.
10.0
1.4.1.1. Differences between int
and float
#
float
occupies a fixed amount of space, whileint
takes up a variable amount of space.int
values are stored asbignum
data type behind the scenes.
import sys
sys.getsizeof(2.0)
Out[3]: 24
sys.getsizeof(2**30)
Out[4]: 32
sys.getsizeof(2**130)
Out[6]: 44
Both
int
andfloat
can store both positive and negative numbers.The
type()
function is used to determine the data type.float
can only represent approximations of real numbers due to the finite amount of memory available in computers.2/3
vs1/3
2 / 3
0.6666666666666666
5 / 3
1.6666666666666667
If you do not need fraction values, use
int
.