Hide

Problem A
Number Validation

Write a function named is_float(string_to_test) that takes one argument that is a string. It returns True if the string string_to_test represents a floating point value and returns False otherwise.

You are required to use try-except. The basic concept is to try to convert string_to_test to a float and if it succeeds, return True, but if it fails (that is, an exception is raised), return False. Note that float() raises a ValueError exception.

You should probably not need to implement any helper functions for this task, but if you wish, you are welcome to do so, although then you are probably overcomplicating things, as there is not much code required to solve this.

Submission instructions

Note that we are testing this function specifically, so your solution must define it. Please only submit your function definition(s), without any code outside the function(s)!

No code is necessary other than your function definition(s), but your solution can contain other code if you can’t be bothered to remove it, as long as it is restricted to if __name__ == "__main__": so it will not run when your function is imported. The main python file, which handles input and output, is already included in the setup of the problem.

You can download and the attached main file in the same directory as your python file, and supply the name of your python file for importing the function is_float in the main file. You can then run the main python file we provide to try out the samples. See also the given starter code for an alternative setup.

Input

Your function should accept one parameter, called string_to_test, expected to be of type str. In this description, we will refer to the input string as $s$, for short. The autograder will handle reading the input for you. The input will consist of a single line containing a string, and that will be passed as an argument to your function.

For your information, in the test cases, the input string $s$ will have at most $20$ symbols, consisting of English letters, digits, spaces, and various symbols. To be specific, each symbol has an ASCII value between $32$ and $126$, inclusive. You do not need to validate the input, or refuse other input, this is just to inform you that you do not need to worry about other kinds of input.

Output

Your function should return a boolean value, indicating if the string $s$ can be interpreted as a float or not. The autograder will handle printing the output for you. The output should consist of one line with either a True or False.

Sample Input 1 Sample Output 1
3.45
True
Sample Input 2 Sample Output 2
3e4
True
Sample Input 3 Sample Output 3
.5
True
Sample Input 4 Sample Output 4
abc
False
Sample Input 5 Sample Output 5
4.x
False

Please log in to submit a solution to this problem

Log in