0

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: ''
3
  • assert is what you are looking for.
    – FatihAkici
    Commented Jun 25, 2019 at 2:20
  • try and except works here too. You never checked for empty string. Also use isinstance to check type.
    – pault
    Commented Jun 25, 2019 at 2:21
  • There is no such thing as "null" in Python. The closest thing is the None object, but you've listed that separately. Commented Jun 25, 2019 at 2:23

2 Answers 2

1

Something like this is better handled using try/except rather than building blocks to handle every case you might encounter.

def get_num_diff(first_num, second_num):
    try:
        first_num = int(first_num)
        second_num = int(second_num)
    except (ValueError, TypeError):
        return 'NA'
    return first_num - second_num
1
  • Thanks. That makes sense..I was trying to think of ways to capture all cases. This works way better
    – Cryssie
    Commented Jun 25, 2019 at 2:40
0

You can check for an empty string with an if statement.

test = ""
if not test:
    print("This test string is empty")

test = "Not Empty"
if test:
    print("This test string is not empty")

Below is example output:

>>> test = ""
>>> if not test:
...     print("This test string is empty")
... 
This test string is empty
>>> test = "Not Empty"
>>> if test:
...     print("This test string is not empty")
... 
This test string is not empty
2
  • Not applicable here since op has numeric values, including possibly 0
    – pault
    Commented Jun 25, 2019 at 2:37
  • It is applicable if OP decides to use it after they check if what is passed is a string. Commented Jun 25, 2019 at 2:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.