Implement IsNumber() function in Python
In this article we will see how to implement isNumber() method using Python. This method takes in a string as input and returns True or False according to whether the string is a number or not.
Input : "12345" Output : True Input : "-12345" Output : True Input : "abc" Output : False
Here we will take advantage of the int() built-in function available in Python. Also with this approach we will see how Exception Handling comes to our aid. Using try-catch construct we try to convert the string to integer. In case the string cannot be converted the handler catches the exception that is thrown.
Below is the Implementation:
For input '9748513' isNumber() returned : True For input '-9748513' isNumber() returned : True For input 'GeeksforGeeks' isNumber() returned : False
Note : This is not the only way to implement the isNumber() function but it is arguably the fastest way of doing so. Try/Catch doesn’t introduce much overhead because the most common exception is caught without an extensive search of stack frames.