Numeric Data Types
Let us explore the following scenario:
x = 7 y = 3 z = x/y print(z)
>> 2.33333333333333333
The output we got is not a whole number. This value is known as a float. A float value uses a decimal to account for numbers with fractional values.
That said, there are two Python data types that are used to denote numeric values:
int
for integer valuesfloat
for decimal value
Determining the type of a Data Type
We can use the type function to determine the data type of a certain value:
x = 7 print(type(x))
>> <class 'int'>
this prints out the type of x denoted as int
If I change x to a decimal number:
x = 7.0 print(type(x))
>> <class 'float'>
Operations on different Data Types
What would happen if you performed a mathematical operation on two different types:
print(2 + 2.5)
>> 4.5
Adding an int and a float together always defaults to a float.
Now what can we expect to happen if we divided two integers together:
print(2/2)
>> 1.0
A division in python will always net a float data type.
Converting Numeric Data Types
let's assume the following operation:
print(7/3.5)
>> 2.0
In order to force the output to be an integer, we can wrap our operation with the integer data type int
like so:
print(int(7/3.5))
>> 2
wrapping a decimal with int
will cut off anything beyond the decimal and return it as an integer.
print(int(3.7))
>> 3
Accordingly, you can convert an integer to a float by wrapping the integer with the float data type float
.
some_float = float(3)
>> 3.0
That is the basic gist behind numerical types. You'll come across these data types very often throughout this course so it's very important to be aware of their distinctions.
In the next article, we'll look at string data types.