So, I've approached an obstacle in a programming exercise. I understand the concept of try except but how can I use a try except handler to only accept a float or decimal and if a whole number or integer is entered, it throws an error message. I know in theory it's not possible but is there a way?
Ideally I want to use a try except block of code as that's the current lesson I am on.
Thanks to all in advance!
Use the isinstance() function to check if a number is an int or float, e.g. if isinstance(my_num, int): . The isinstance function will return True if the passed in object is an instance of the provided class ( int or float ).
To check if the variable is an integer in Python, we will use isinstance() which will return a boolean value whether a variable is of type integer or not. After writing the above code (python check if the variable is an integer), Ones you will print ” isinstance() “ then the output will appear as a “ True ”.
Check if the value has a type of number and is not an integer. Check if the value is not NaN . If a value is a number, is not NaN and is not an integer, then it's a float.
How about using .is_integer()
on float
?
>>> float(5).is_integer()
True
>>> float(5.12).is_integer()
False
>>>
so
if float(x).is_integer():
raise ValueError('Non integers please')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With