Is using nested try-except an acceptable Python style here - python

I need check whether the string price is an integer or a float and return True in this case or False otherwise.
Is this function written in an acceptable Python style?
def is_valid_price(price):
try:
int(price)
return True
except:
try:
float(price)
return True
except:
return False
If no, what's the best way to make it look Pythony?

Definitely not — except without specifying the exception class(es) is prone to make problems.
def is_valid_price(price):
try:
float(price)
return True
except ValueError:
return False
There is no need to use test int(price), because if the string is convertible to int, it's also convertible to float.

In this case you only check type of price:
def is_valid_price(price):
return isinstance(price, (int, float))
is_valid_price(5)
You can call exception
assert float(price)
if price not float(int) you will get exception
ValueError Traceback (most recent call last)
in ()
----> 1 assert float(price)
ValueError: could not convert string to float: price

Related

Pass a keyword variable to a function as an argument

I'm doing a project that is requiring a lot of input validation. I currently have a function defined as follows:
def get_valid_float(inputMessage,errorMessage):
while True:
variableInput = input(inputMessage)
try:
variableInput = float(variableInput)
return variableInput
except ValueError:
print(errorMessage)
This function allows me to choose a custom message to prompt the user. It will then validate that the user input is indeed a float, and will print a custom error message in the event that it is not. It will loop until the user gives a valid input.
However, I would rather not create a function to validate each and every data type. It seems like it would be best to combine these into one get_valid_input() function, and pass a third argument allowing me to choose what data type I am attempting to verify. For example, get_valid_input(complex,inputMessage,errorMessage).
I am obviously unable to pass a keyword as an argument. This makes me think the only way to do this would to be to do something like this:
def get_valid_float(dataType,inputMessage,errorMessage):
if dataType == "float"
while True:
variableInput = input(inputMessage)
try:
variableInput = float(variableInput)
return variableInput
except ValueError:
print(errorMessage)
elif dataType == "integer"
while True:
variableInput = input(inputMessage)
try:
variableInput = int(variableInput)
return variableInput
except ValueError:
print(errorMessage)
And so on, with an elif for every data type. Surely there is an easier way to do this, that somehow allows me to execute the line variableInput = {dataType}(variableInput) to confirm that they input a value of data type "dataType". Any ideas?
Just pass as an argument the actual data type, rather than the name of the data type. E.g:
def get_valid_input(dataType, inputMessage, errorMessage):
while True:
value = input(inputMessage)
try:
value = dataType(value)
break
except ValueError:
print(errorMessage)
You would call it like this:
floatvalue = get_valid_input(float, "enter a float value: ", "that is an invalid float")
intvalue = get_valid_input(int, "enter an integer value: ", "that is an invalid integer")
I am obviously unable to pass a keyword as an argument.
Not sure why you're saying that, but you can! :)
Also no need for error message, just catch all Exceptions (Not recommended but since you are just printing out the error it seems fine here)
The message strings aren't really needed, try using the name of the dataType and the exception's message like this:
def get_valid_data(dataType):
while True:
variableInput = input(f"Put in data of type {dataType.__name__}: ")
try:
variableInput = dataType(variableInput)
return variableInput
except Exception as e:
print(e)
get_valid_data(int)
>>> Put in data of type int: "hi"
>>> invalid literal for int() with base 10: '"hi"'

How to Check data is int, float in 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

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.

Accepting either a string or an integer for a date

How to check whether the parameter I passed in function is integer, string or date in python?
My function can accept either a string or an integer as the date:
def check(self, dat1):
# print(self.path)
# dat1 = raw_input("data = ")
print(type(dat1))
try:
datetime.datetime.strptime(dat1, '%Y-%m-%d')
except ValueError:
try:
int(dat1)
except ValueError:
print("str it is")
else:
print(dat1)
rand1 = random.randint(int(dat1) - (int(dat1) % 7), int(dat1) + (int(dat1) % 7))
print(rand1)
return rand1
else:
print("date it is")
check(100)
I get an error like this when I pass in an integer:
datetime.datetime.strptime(dat1, '%Y-%m-%d')
TypeError: must be string, not int
I know there is a question similar but it works for raw_input() not for parameter.
The first argument to the datetime.datetime.strptime() method must be a string. You are passing it an integer instead, and that means a TypeError is raised.
Catch that exception too, and not just ValueError (which is thrown if you pass in the right type but the string could not be parsed):
try:
datetime.datetime.strptime(dat1, '%Y-%m-%d')
except (ValueError, TypeError):
You could try using isinstance
>>> my_str = "Foo"
>>> isinstance(my_str, str)
True
>>> my_int = 1234
>>> isinstance(my_int, int)
True
>>> my_date = datetime.date.today()
>>> isinstance(my_date, datetime.date)
True
# Assuming you used "import datetime" at the top of your file
You could then use a if-elif structure to raise appropriate exceptions.

Adding print statement to ValueError exception

New to Python, so I'm sure this is a noob question, but Googling isn't availing me of a clear answer.
Given the following function which is intended to ensure that the user input is a string, why can't I (or how can I) add a print statement when the exception is triggered? The print statement I've inserted there doesn't work.
def string_checker(action):
try:
check = isinstance(action, basestring)
if check == True:
return True
except ValueError:
print "We need a string here!"
return None
action = "words"
string_checker(action)
This may do what you want:
def string_checker(action):
try:
assert isinstance(action, basestring)
return True
except AssertionError:
print "We need a string here!"
return None
action = "words"
string_checker(action)
string_checker(21)
But you could also return "We need a string here!" instead of printing it, or return False, for consistency.
The problem is that you're never raising a value error if action isn't a string. Try this:
def string_checker(action):
try:
check = isinstance(action, basestring)
if check:
return True
else:
raise ValueError
except ValueError:
print "We need a string here!"
return None
But really, I don't think you need an exception. This should work fine:
def string_checker(action):
try:
check = isinstance(action, basestring)
if check:
return True
else:
print "We need a string here!"
return None
I'm not sure I understand. This appears to print "We need a string here!":
def string_checker(action):
try:
raise ValueError()
check = isinstance(action, basestring)
if check == True:
return True
except ValueError:
print "We need a string here!"
return None
action = "words"
string_checker(action)
raw_input('#')
Note the raise ValueError() in the try. Are you sure an exception is being thrown?

Categories