In Python, floating-point numbers or ‘floats’ are a sort of data type that identifies numerical values with decimal points.
When building applications or software, you may require users to input this type of number.
This makes it necessary to discern whether a user’s input is indeed a ‘float’. This tutorial will guide you on how to check if an input is a float using Python.
Step 1: Taking user input
The first step would be capturing the user’s input. Here, we use Python’s built-in function, input() to get this user’s input.
1 |
user_input = input("Enter a number: ") |
Step 2: Checking if the input is a float
To check if this input is a float, we use Python’s built-in function, float(), inside a try-except block. If the input can be converted to a float, it means the input is a float or an integer (since integers can be presented as floating-point numbers). If the input cannot be converted to a float, it would raise a ValueError, and we know the input is not a float.
1 2 3 4 5 |
try: float(user_input) print("The input is a float number.") except ValueError: print("The input is not a float number.") |
Step 3: Differentiating between a float and an integer
If you want to differentiate an integer from a float, you can further check if the float number has a zero fraction part. You can accomplish this by checking if the number remains the same after converting it to an integer using Python’s built-in function, int().
1 2 3 4 5 6 7 8 |
try: val = float(user_input) if val == int(val): print("The input is an integer number.") else: print("The input is a float number.") except ValueError: print("The input is not a float or integer number.") |
Full Code
1 2 3 4 5 6 7 8 9 10 |
user_input = input("Enter a number: ") try: val = float(user_input) if val == int(val): print("The input is an integer number.") else: print("The input is a float number.") except ValueError: print("The input is not a float or integer number.") |
Enter a number: 5 The input is an integer number.
Enter a number: text The input is not a float or integer number.
Enter a number: 5.6 The input is a float number.
Conclusion
This simple tutorial demonstrates how to check if a user input is a float number in Python. Note that integers can be represented as floats, and additional steps should be taken when it’s necessary to differentiate between the two.
In Python, any data type can rapidly be checked and verified, adding flexibility and agility to your code.