-2

Having trouble running this code accurately.

When checking values if its greater or equal or less than the next value. Not sure how to make it print unknown if the value is not an int.

def check(x, y):
    if x == y:
        return 'equal'
    if a > b:
        return 'greater than'
    if x < y:
        return 'less than'
    #how can I add a line of code to return 'NA" if is not an int:
        return "NA"
check(5, 5)
check('r', 5)

Guidance is appreciated.

Smuuf
  • 6,339
  • 3
  • 23
  • 35
  • 1
    See [the docs](https://docs.python.org/3/tutorial/errors.html#handling-exceptions) on error handling for some ideas, you can use try:except to catch errors when values can't be compared, or you can check the types of your inputs before you do the comparison with `isinstance()` and `return` is the inputs aren't numeric. Also, you mix `a`,`b` and `x`,`y` in your posted code – G. Anderson Oct 14 '20 at 00:28
  • 1
    How do you want to treat *str* values? Are they invalid? Should you use ASCII values? – Joonyoung Park Oct 14 '20 at 00:30
  • No I would just have it return NA – StackSuperLow Oct 14 '20 at 00:33

2 Answers2

1

You can use the isinstance function to check whether a value is an instance of some type (this takes class hierarchy into account).

def check(x, y):
    if not isinstance(x, int) or not isinstance(y, int):
        return "NA"
    if x == y:
        return 'equal'
    if a > b:
        return 'greater than'
    if x < y:
        return 'less than'

If you want to check int or float, you can use this condition instead:

if not isinstance(x, (int, float,)) or not isinstance(y, (int, float,)):
    ...
Smuuf
  • 6,339
  • 3
  • 23
  • 35
0

You can use isinstance to check whether passed argument are ints. Sample code below.

def check(x, y):
  if isinstance(x, int) and isinstance(y,int):
    if x == y:
      return 'equal'
    if x > y:
      return 'greater than'
    if x < y:
      return 'less than'
  return("NA")
print(check(5,5))
print(check('r',5))
ewin.str
  • 109
  • 1
  • 9