How to Check data is int, float in python - python

I know similar questions have been asked and answered before like here: How do I check if a string is a number (float or Int ) in Python?
However, it does not provide the answer I'm looking for. What I'm trying to do is this:
def is_int_or_float(s):
try:
a = float(s)
return 1 if s.count('.')==0 else 2
except ValueError:
return -1
val = input("Enter your value: ")
data = is_int_or_float(val)
print(data)
What if User enters => "22" # Then Above code will gives -1.Please help me to resolve this With Exception handling (User Message)

Try this:
def is_int_or_float(value):
try:
tmp = float(value)
return 1 if tmp.is_integer() else 2
except ValueError:
return -1
And testing:
>>> is_int_or_float("a")
-1
>>> is_int_or_float("22")
1
>>> is_int_or_float("22.646")
2
>>> is_int_or_float("22.64.6")
-1
>>> is_int_or_float("22.000")
1
>>> is_int_or_float("1e-4")
2

You can create a simple handle for that.
Check the code. You need to implements you exception handle logic.
class AbstractHandler:
def is_float(self):
raise NotImplementedError
def is_int(self):
raise NotImplementedError
def verify(self):
raise NotImplementedError
class Handler(AbstractHandler):
def is_float(self, number):
try:
float(number)
return True
except ValueError:
# Your exception handler here
return False
def is_int(self, number):
try:
int(number)
return True
except ValueError:
# Your exception handler here
return False
def verify(self, var):
if self.is_float(var) or self.is_int(var):
return True
else:
return False
def is_number(var):
"""
Verify if input is a instance of int or float
Args:
var (str): input to be verified
"""
handler = Handler()
return handler.verify(var)
Some tests:
1 is True
1.1 is True
1.1.1 is False

One way to check, for example integer, use isinstance:
x = 1
if isinstance(x, int):
# Do something

Related

User defined exception error using try and except

I am trying to create a user defined exception in the below quadratic roots program (using classes).
The intention is to throw and error back if the input list length is not 3 (need 3 inputs for the 3 coefficients). Additionally, I would want the code to stop executing if there is an input error.
However, this code isn't working, it doesn't throw an exception and the code continues to execute.
Would greatly appreciate if you could guide me.
class quadRoots():
def __init__(self,coeff):
self.A = coeff[0]/coeff[0]
self.B = coeff[1]/coeff[0]
self.C = coeff[2]/coeff[0]
self.Z = 0
self.R_1 = 0
self.R_2 = 0
self.coeff = len(coeff)
try:
self.coeff == 3
except:
print("Input size is not valid")
def roots(self):
import cmath
self.Z = cmath.sqrt((self.B**2)/4 - (self.C))
self.R_1 = ((-(self.B)/2) + self.Z)
self.R_2 = ((-(self.B)/2) - self.Z)
return [self.R_1,self.R_2]
def mult(self):
return quadRoots.roots(self)[0] * quadRoots.roots(self)[1]
def sumRoots(self):
return [complex(-(self.B))]
def prodRoots(self):
return [complex(self.C)]
quadroots([1,-9,14,15]).roots()
try:
self.coeff == 3
except:
print("Input size is not valid")
A Try-Except Chain doesn't work like this. It works when there is an error. But here, there is no error. I suggest you use assert self.coeff == 3, "Input size is not valid". instead, it raises an error, and exits the program, if self.coeff is not equal to 3.
so then the whole try except chain can be replaced by one line. assert self.coeff == 3, "Input size is not valid"

Apply a function and check custom exceptions with decorators

I want to write a function that check a condition (with custom exceptions) and if no exceptions are raised it applies a function and return the result.
# Custom exceptions
class NegativeNumber(Exception):
pass
class BigNumber(Exception):
pass
def add_two(number):
return number + 2
def apply_function(number, f):
def check_condition(number, f):
try:
if number < 0:
raise NegativeNumber
if number > 10:
raise BigNumber
except NegativeNumber:
return ("Negative Number")
except BigNumber:
return ("Big Number")
return (f(number))
return check_condition(number, f)
apply_function(5, add_two)
Can be this code written better using decorators?
You've already done most of it. I modified your function name and the structure of your code a bit. This should be what you are looking for:
# Custom exceptions
class NegativeNumber(Exception):
pass
class BigNumber(Exception):
pass
def check_exceptions(f):
def wrapped(number):
try:
if number < 0:
raise NegativeNumber
if number > 10:
raise BigNumber
except NegativeNumber:
return "Negative Number"
except BigNumber:
return "Big Number"
return f(number)
return wrapped
#check_exceptions
def add_two(number):
return number + 2
for num in (-1, 5, 15):
print(add_two(num))
Output:
Negative Number
7
Big Number

Instead of isinstance, use of try and except in Python 3.7

I wrote a code to catch my error message using try and except (I want to write it without using isinstance) and I am getting the error message when the input is not an integer. The problem is, the program is giving me error message even if the input is valid integer. Please give me some suggestions to make it run. My code is given below:
I tried using exception clause but that did not work.
class Hotel:
def __init__(self,room,catagory):
if room != int:
raise TypeError ()
self.room = room
self.catagory = catagory
self.catagories = {"A":"Elite","B":"Economy","C":"Regular"}
self.rooms = ["0","1","2","3","4","5"]
def getRoom(self):
return self.room
def getCatagory(self):
return self.catagory
return self.catagories.get(self.catagory)
def __str__(self):
return "%s and %s"%(self.rooms[self.room],self.catagories.get(self.catagory))
try:
room1 = Hotel(a,"A")
room2 = Hotel(1,"A")
print(room1.getRoom())
except:
print("there's an error")
I am expecting:
there's an error
1 and Elite
A
You are checking if room != int . It will give you error always.
You have to check type(room)!= int .
I have corrected the code below
class Hotel:
def __init__(self,room,catagory):
if type(room) != int:
raise TypeError ()
self.room = room
self.catagory = catagory
self.catagories = {"A":"Elite","B":"Economy","C":"Regular"}
self.rooms = ["0","1","2","3","4","5"]

except ValueError in Python

Is there better way of writing this code:
def add (exe1, exe2):
try:
a = float (exe1)
b = float (exe2)
total = float (a + b)
except ValueError:
return None
else:
return total
You can have it all inside a try/except block (calculation and return):
def add(exe1, exe2):
try:
return float(exe1) + float(exe2)
except ValueError:
return None
Also note, the default return value from function is None, so the second return is not really necessary (you could have pass instead), but it makes code more readable.
You can also use contextlib.suppress, if you find it more readable.
from contextlib import suppress
def add(exe1, exe2):
with suppress(ValueError):
return float(exe1) + float(exe2)
See the documentation here.

How to test if exception in ok in unittest

I have a question about unittest.
How to make a test to see if is there an exception?
an example:
Datum(3,32,2012)
If i call class Datum like this, where month is not in range (>31), it's everything OK, it throws an Exception and thats OK. But I want to make an unittest if Exception is OK, if is catching an exception ok..?
I made some test but and these were only with True values, and they are ok. I have no idea how to test in this way.. and search on internet..
thanks for reply.
import date,datetime
class Datum():
def __init__(self,day,month,year):
try:
d=int(day)
dvm=stevilodnivmesecu(month,year)
if (d>=1 and d<=dvm):
self.d=d
else:
raise Exception("Day out of moth range")
except:
raise ValueError("Day is not a number")
try:
m=int(month)
if m>=1 and m<=12:
self.m=m
else:
raise Exception("Month out of range")
except:
raise ValueError("Month is not a number")
try:
l=int(year)
if l>=1000 and l<=9999:
self.l=l
else:
raise Exception("Year is out of range")
except:
raise ValueError("Year is not a number")
def __repr__(self):
return repr(self.d)+"."+repr(self.m)+"."+repr(self.l)
def monthrange(month,year):
if month==2:
if jeprestopno(year)==True:
return 29
elif jeprestopno(year)==False:
return 28
elif month>=1 and month<=7:
if month%2!=0:
return 31
elif month>7 and month<=12:
if month%2==0:
return 31
elif month>=1 and month<=7:
if month%2==0:
return 30
elif month>7 and month<=12:
if month%2!=0:
return 30
else:
pass
def oneplusyear(year):
if year%4==0 or (year!=100 and year%4==0) or (year%400==0 and year%100==0):
return True
else:
return False
Use
self.assertRaises(ValueError,Datum,3,32,2012)
in your unittest.TestCase test to assert that Datum(3,32,2012) raises a ValueError.
Reference:
Documentation on the various types of asserts you can make in
TestCases.

Categories