I'm writing a function that will return a list of square numbers but will return an empty list if the function takes the parameter ('apple') or (range(10)) or a list. I have the first part done but can't figure out how to return the empty set if the parameter n is not an integer- I keep getting an error: unorderable types: str() > int() I understand that a string can't be compared to an integer but I need it to return the empty list.
def square(n):
    return n**2
def Squares(n):
    if n>0:
        mapResult=map(square,range(1,n+1))
        squareList=(list(mapResult))   
    else:
        squareList=[]
    return squareList
                You can use the type function in python to check for what data type a variable is. To do this you would use type(n) is int to check if n is the data type you want. Also, map already returns a list so there is no need for the cast. Therefore...
def Squares(n):
    squareList = []
    if type(n) is int and n > 0:
        squareList = map(square, range(1, n+1))
    return squareList
                        You can chain all the conditions which result in returning an empty list into one conditional using or's. i.e if it is a list, or equals 'apple', or equals range(10) or n < 0 then return an empty list. ELSE return the mapResult.
def square(n):
    return n**2
def squares(n):
   if isinstance(n,list) or n == 'apple' or n == range(10) or n < 0:
      return []
   else:
      return list(map(square,range(1,n+1)))
isinstance checks if n is an instance of list.
Some test cases:
print squares([1,2])
print squares('apple')
print squares(range(10))
print squares(0)
print squares(5)
Gets
[]
[]
[]
[]
[1, 4, 9, 16, 25]
>>> 
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With