Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Try Except float but not integer

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!

like image 363
Gallieon474 Avatar asked Oct 07 '15 21:10

Gallieon474


People also ask

How do you check if a value is an integer or a float in Python?

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 ).

How do you test if a value is an integer in Python?

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 ”.

How do you know if a number is a float?

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.


1 Answers

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')
like image 172
karthikr Avatar answered Oct 25 '22 23:10

karthikr