0

When I run this code; even when the list contains only numbers, it still returns as an error when it should return [1, 2, 3]. How can I fix this issue?

def check_integer(a, b, c):

  if type([a, b, c]) !=  int:
    raise TypeError("Must be numbers.")
  else:
    return [a, b, c]

print (check_integer(1, 2, 3)) 
saturns
  • 57
  • 6

4 Answers4

1

try using all and iterate over each elements:

def check_integer(a, b, c):

    if not all(type(i)==int for i in [a,b,c]):
        raise TypeError("Must be numbers.")
    else:
        return [a, b, c]

print (check_integer(1, 2, 3)) 

[1, 2, 3]

Efficient way of doing:

def check_integer(*params):

    if not all(type(i)==int for i in params):
        raise TypeError("Must be numbers.")
    else:
        return params

print (check_integer(*[1,2,3])) 
Pygirl
  • 12,969
  • 5
  • 30
  • 43
0
def check_integer(a, b, c):

  if not (type(a) is int and type(b) is int and type(c) is int):
    raise TypeError("Must be numbers.")
  else:
    return [a, b, c]


print(check_integer(1, 2, 3))

this is correct code.

0

A generalized solution:

def check_integer(*args):
    if not all([type(i) == int for i in [*args]]):
        raise TypeError("Must be numbers.")

    return args
nocibambi
  • 2,065
  • 1
  • 16
  • 22
0

This is a way to do it:

def check_integers(*args):

    if not all(isinstance(i, int) for i in args):
        raise TypeError("Must be numbers.")
    
    return list(args)

You can add other types in the second argument of isinstance as a tuple (ej. isinstance(var, (int, float))).

JMA
  • 803
  • 4
  • 9