Try; try again

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.

1 Like

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

Not sure why it fell through.

1 Like

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

1 Like