Cryssie
Cryssie

Reputation: 3175

Pythonic way of checking null and empty string

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:

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: ''

Upvotes: 0

Views: 707

Answers (2)

Evan Bloemer
Evan Bloemer

Reputation: 1081

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

Upvotes: 0

James
James

Reputation: 36598

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

Upvotes: 1

Related Questions