Algorithm
-
Input: Accept a string as input.
-
Function Definition (is_float):
- Define a function
is_floatthat takes a string as a parameter.
- Define a function
-
Try-Except Block:
- Use a
tryblock 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
Truefrom the function. - If a
ValueErroroccurs during conversion, catch the error in theexceptblock. - In the
exceptblock, returnFalsesince 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_floatfunction 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_floatfunction.
- 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