In this step, you will learn to differentiate between two fundamental data types in Python: integers and floats. Understanding the difference is crucial for performing accurate calculations and data manipulation.
Integers are whole numbers, positive or negative, without any decimal points. Examples include -3, 0, 5, 100.
Floats, or floating-point numbers, are numbers that contain a decimal point. They can also represent numbers in scientific notation. Examples include -2.5, 0.0, 3.14, 1.0e5 (which is 100000.0).
Let's start by creating a Python script to explore these data types.
-
Open the VS Code editor in the LabEx environment.
-
Create a new file named datatypes.py
in the ~/project
directory.
touch ~/project/datatypes.py
-
Open the datatypes.py
file in the editor and add the following Python code:
## Assign an integer to the variable 'integer_number'
integer_number = 10
## Assign a float to the variable 'float_number'
float_number = 10.0
## Print the values and their types
print("Integer:", integer_number, "Type:", type(integer_number))
print("Float:", float_number, "Type:", type(float_number))
-
Save the datatypes.py
file.
-
Run the script using the python
command in the terminal:
python ~/project/datatypes.py
You should see the following output:
Integer: 10 Type: <class 'int'>
Float: 10.0 Type: <class 'float'>
This output clearly shows that integer_number
is of type int
and float_number
is of type float
.
-
Now, let's perform a simple arithmetic operation to see how Python handles these types:
Modify the datatypes.py
file to include the following:
## Assign an integer to the variable 'integer_number'
integer_number = 10
## Assign a float to the variable 'float_number'
float_number = 10.0
## Print the values and their types
print("Integer:", integer_number, "Type:", type(integer_number))
print("Float:", float_number, "Type:", type(float_number))
## Add an integer and a float
sum_result = integer_number + float_number
## Print the result and its type
print("Sum:", sum_result, "Type:", type(sum_result))
-
Save the datatypes.py
file.
-
Run the script again:
python ~/project/datatypes.py
You should see the following output:
Integer: 10 Type: <class 'int'>
Float: 10.0 Type: <class 'float'>
Sum: 20.0 Type: <class 'float'>
Notice that when you add an integer and a float, the result is a float. This is because Python automatically converts the integer to a float to maintain precision.