Algorithm
-
Input: Accept a string as input.
-
Function Definition (is_float):
- Define a function
is_float
that takes a string as a parameter.
- Define a function
-
Try-Except Block:
- Use a
try
block to encapsulate the following code:- Attempt to convert the input string to a float using
float(string)
. - If successful, set the result to a variable (e.g.,
float_value
).
- Attempt to convert the input string to a float using
- Use a
-
Return True or False:
- If the conversion is successful, return
True
from the function. - If a
ValueError
occurs during conversion, catch the error in theexcept
block. - In the
except
block, returnFalse
since the string is not a valid floating-point number.
- If the conversion is successful, return
-
Example Usage:
- Get user input (string) to check if it is a valid floating-point number.
- Call the
is_float
function with the user input as an argument.
-
Output:
- Display a message indicating whether the input string is a valid floating-point number based on the return value of the
is_float
function.
- Display a message indicating whether the input string is a valid floating-point number based on the return value of the
Code Examples
#1 Code Example with Python Programming
Code -
Python Programming
def is_float(string):
try:
float_value = float(string)
return True
except ValueError:
return False
# Example usage:
user_input = input("Enter a string: ")
if is_float(user_input):
print(f"{user_input} is a valid floating-point number.")
else:
print(f"{user_input} is not a valid floating-point number.")
Copy The Code &
Try With Live Editor
Output
Enter a string: 3.14
3.14 is a valid floating-point number.
3.14 is a valid floating-point number.
Demonstration
Python Programing Example to Check If a String Is a Number (Float)-DevsEnv