Reputation: 1
Im trying to decide whether a string variable is a valid integer or float, ive tried try statements but using ASCII seems to be better. I can't get this to work, probably something with the returns and boolean.
def validation(valid):
var=input("no...")
state=True
y=0
for x in range(len(var)):
if state==False or y==2:
valid=False
return valid
if var[x] == chr(46) or chr(48) <= var[x] <= chr(57):
if var[x] == chr(46):
y+=1
state=True
else:
state=False
valid=True
valid = validation(valid)
print(valid)
The ASCII characters 46 and 48-57 are a decimal point and numbers 0-9. If there more than one decimal point (representing by y) than it also returns a false statement.
Upvotes: 0
Views: 64
Reputation: 55469
Your code isn't very efficient, and it doesn't handle negative numbers, or floats written in scientific notation. Using try
, as in fiacre's answer is the standard way to do this in Python.
But to answer your question, you don't have a return
statement after the for
loop, so if all your tests succeed your function returns the default value of None
. So you just need to put a return True
at the end of your function.
You can make your code a little more efficient by iterating over the string values and testing the characters directly rather than indexing into the string and using chr()
. Eg,
for c in var:
if c == '.' or '0' <= c <= '9':
# etc
Alternatively,
valid_chars = set('-.0123456789')
for c in var:
if c in valid_chars:
# etc
FWIW, in your existing code Python has to re-calculate chr(46)
etc on every loop. Sure, that's a pretty fast operation, but it's still wasteful.
Also, there's no need to have both state
and valid
in the function.
Upvotes: 1
Reputation: 1180
There is a much simpler way to do this:
try:
float(x)
except ValueError as e:
print e
print "Not a float"
else:
try:
int(x)
except ValueError as e:
print e
print "not an integer"
You can combine these into a method pretty easily.
Upvotes: 1
Reputation: 1011
Simple and powerful approach:
def isNum(txt):
try:
float(txt)
return True
except ValueError:
return False
Upvotes: 2