On 24/04/20 1:24 PM, Deac-33 Lancaster wrote:
I'm aware that you can find the type of a variable with
type(var)
But are there Boolean operators in Python3.8 to test the data type, e.g.
is_floate(var)
is_string(var)
etc. ?
There is also a 'pythonic' answer (what is the 'Python way'?) and that
is to proceed on the basis of "duck typing" and 'presumption'. The
latter known as EAFP ("It's Easier To Ask Forgiveness Than To Get
Permission"), eg:
>>> n = 2
>>> d = 'two'
my training/first inclination has always been to check before use - in
this case, that both the numerator and denominator are numeric and that
the latter is non-zero - seeking to avoid:
>>> n / d
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for /: 'int' and 'str'
Crash!
Conversely, here is the pythonic EAFP approach:
>>> try:
... n / d
... except TypeError:
... print( "I'm sorry, Dave. I'm afraid I can't do that." )
...
I'm sorry, Dave. I'm afraid I can't do that.
>>>
and if you want to go all-in and try to break the laws of mathematics:
>>> n = 2
>>> d = 0
>>> try:
... n / d
... except TypeError:
... print( "I'm sorry, Dave. I'm afraid I can't do that." )
... except ZeroDivisionError:
... print( "Officer, it wasn't me - honest!" )
...
Officer, it wasn't me - honest!
>>>
or just-for-fun:
>>> try:
... n / d
... except ( ZeroDivisionError, TypeError ):
... print( "I'm sorry, Dave. I'm afraid I can't do that." )
...
I'm sorry, Dave. I'm afraid I can't do that.
--
Regards =dn
--
https://mail.python.org/mailman/listinfo/python-list