Learn About Floating-Point Numbers
In this step, you will learn about floating-point numbers in Python. Floating-point numbers are used to represent real numbers, which include numbers with decimal points. Understanding how to work with floating-point numbers is crucial for many types of calculations.
Let's start by creating a Python file to experiment with floating-point numbers.
- Open the VS Code editor in the LabEx environment.
- Create a new file named
floats.py
in the ~/project
directory.
Now, let's add some code to floats.py
:
## Assigning floating-point numbers to variables
pi = 3.14159
gravity = 9.8
temperature = 25.5
## Printing the values
print("Pi:", pi)
print("Gravity:", gravity)
print("Temperature:", temperature)
In this code, we've assigned floating-point values to three variables: pi
, gravity
, and temperature
. The print()
function is then used to display these values.
To run the script, open a terminal in VS Code (you can usually find it in the menu under "View" -> "Terminal") and execute the following command:
python floats.py
You should see the following output:
Pi: 3.14159
Gravity: 9.8
Temperature: 25.5
Now, let's perform some basic arithmetic operations with floating-point numbers:
## Addition
result_addition = pi + gravity
print("Addition:", result_addition)
## Subtraction
result_subtraction = gravity - temperature
print("Subtraction:", result_subtraction)
## Multiplication
result_multiplication = pi * temperature
print("Multiplication:", result_multiplication)
## Division
result_division = gravity / 2
print("Division:", result_division)
Add these lines to your floats.py
file and run it again:
python floats.py
You should see output similar to this:
Pi: 3.14159
Gravity: 9.8
Temperature: 25.5
Addition: 12.94159
Subtraction: -15.7
Multiplication: 80.110545
Division: 4.9
Floating-point numbers can also be expressed using scientific notation:
## Scientific notation
avogadro = 6.022e23
print("Avogadro's number:", avogadro)
Add this to your floats.py
file and run it:
python floats.py
The output will be:
Pi: 3.14159
Gravity: 9.8
Temperature: 25.5
Addition: 12.94159
Subtraction: -15.7
Multiplication: 80.110545
Division: 4.9
Avogadro's number: 6.022e+23
This demonstrates how to define and use floating-point numbers in Python, including basic arithmetic operations and scientific notation.