Try; try again

python

#1

For whatever reason this just came up and it seemed a useful bit to share…

>>> def is_num(x):
	try:
		return (abs(x) + 1 or False) and True
	except:
		try:
			return (abs(float(x)) + 1 or False) and True
		except:
			return "Input Error!"

		
>>> is_num('3.14')
True
>>> from math import pi
>>> is_num(pi)
True
>>> is_num(str(pi))
True
>>> is_num('3.14...')
'Input Error!'
>>> 

The expected return is boolean or error message.


#2

Did some tinkering, I really expected to see something like
TypeError: bad operand type for abs(): ‘str’

Not sure why it fell through.


#3

Were you trying to write, abs(str(x))?