I have a simple function that takes 2 params and subtract the first param with the second param.
The function should also do the following:
- Check both params are not null, None or empty string
- Check both params are numeric
- Convert numbers in string into integer (e.g. '7' --> 7)
I am getting errors if empty string is passed in as one of the params. How to write this function in a pythonic way without adding additional checks for empty string?
def get_num_diff(first_num, second_num):
if ((first_num is not None) & (second_num is not None)):
if (type(first_num) is str):
first_num = int(first_num)
if type(second_num) is str:
second_num = int(second_num)
return first_num - second_num
else:
return 'NA'
Error:
invalid literal for int() with base 10: ''
assert
is what you are looking for.try
andexcept
works here too. You never checked for empty string. Also useisinstance
to check type.