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.
Examples:
Input : "12345" Output : True Input : "-12345" Output : True Input : "abc" Output : False
Approach :
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 Implementaion:
# Implementation of isNumber() function def isNumber(s): # handle for negative values negative = False if(s[0] =='-'): negative = True if negative == True: s = s[1:] # try to convert the string to int try: n = int(s) return True # catch exception if cannot be converted except ValueError: return False s1 = "9748513"s2 = "-9748513"s3 = "GeeksforGeeks" print("For input '{}' isNumber() returned : {}".format(s1, isNumber(s1))) print("For input '{}' isNumber() returned : {}".format(s2, isNumber(s2))) print("For input '{}' isNumber() returned : {}".format(s3, isNumber(s3))) |
Output :
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.
Recommended Posts:
- Implement sigmoid function using Numpy
- Implement your own word2vec(skip-gram) model in Python
- Python | Program to implement simple FLAMES game
- Python | Program to implement Jumbled word game
- Python | Program to implement Rock paper scissor game
- How to implement Dictionary with Python3?
- ML | Implement Face recognition using k-NN with scikit-learn
- Implement Token Authentication using Django REST Framework
- Python - Call function from another function
- Python map() function
- Help function in Python
- Python | cmp() function
- id() function in Python
- Python | dir() function
- Python | int() function
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


