Handle Both Integers and Floats
In this step, you will learn how to handle both integers and floating-point numbers (decimals) in your Python program. This is important because you'll often encounter different types of numerical data in real-world applications.
Let's modify the positive_numbers.py
file again to work with floats. Open the positive_numbers.py
file in your ~/project
directory using the VS Code editor.
Now, change the value of the number
variable to a floating-point number, such as 3.14
:
number = 3.14
if number > 0:
print(number, "is a positive number")
elif number == 0:
print(number, "is zero")
else:
print(number, "is a negative number")
Save the file and run the script:
cd ~/project
python positive_numbers.py
You should see the following output:
3.14 is a positive number
Now, let's try a negative floating-point number, such as -2.5
:
number = -2.5
if number > 0:
print(number, "is a positive number")
elif number == 0:
print(number, "is zero")
else:
print(number, "is a negative number")
Save the file and run the script again:
python positive_numbers.py
You should see the following output:
-2.5 is a negative number
As you can see, the program works correctly with both integers and floats. Python automatically handles the different data types without requiring any special modifications to the code. This flexibility makes Python a powerful language for numerical computations.