Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Implement IsNumber() function in Python
In this article, we will learn how to implement an isNumber() function in Python. This custom function checks whether a given string represents a valid number and returns True or False accordingly.
The function uses exception handling with try and except statements to determine if a string can be converted to a number. This approach is efficient because Python's built-in conversion functions will raise a ValueError if the string is not a valid number.
Basic Implementation
Here's a simple implementation that checks for integers ?
def isNumber(s):
# Handle negative numbers
if s[0] == '-':
s = s[1:]
# Exception handling
try:
n = int(s)
return True
# Catch exception if any error is encountered
except ValueError:
return False
# Test cases
inp1 = "786"
inp2 = "-786"
inp3 = "Tutorialspoint"
print(isNumber(inp1))
print(isNumber(inp2))
print(isNumber(inp3))
True True False
Enhanced Version for Floats
To handle both integers and floating-point numbers, we can use float() instead ?
def isNumber(s):
try:
float(s)
return True
except ValueError:
return False
# Test with different number formats
test_cases = ["123", "-45.67", "3.14159", "abc", "12.34.56", ""]
for case in test_cases:
print(f"'{case}' is number: {isNumber(case)}")
'123' is number: True '-45.67' is number: True '3.14159' is number: True 'abc' is number: False '12.34.56' is number: False '' is number: False
Using Built-in Methods
Python provides built-in string methods for specific number checks ?
# Using built-in methods
test_string = "12345"
print(f"isdigit(): {test_string.isdigit()}")
print(f"isnumeric(): {test_string.isnumeric()}")
print(f"isdecimal(): {test_string.isdecimal()}")
# Comparison with custom function
def isNumber(s):
try:
float(s)
return True
except ValueError:
return False
print(f"Custom isNumber(): {isNumber(test_string)}")
isdigit(): True isnumeric(): True isdecimal(): True Custom isNumber(): True
Comparison of Methods
| Method | Handles Negatives | Handles Floats | Best For |
|---|---|---|---|
isdigit() |
No | No | Positive integers only |
isnumeric() |
No | No | Unicode numeric characters |
Custom isNumber()
|
Yes | Yes | All number formats |
Conclusion
The custom isNumber() function using exception handling provides the most flexible solution for detecting numeric strings. Use int() for integers only or float() for comprehensive number validation including decimals and negative numbers.
