Solution 1

def sum_if_list_of_ints(a_list):
    for item in a_list:
        if not isinstance(item, int):
            return 'not an int'
    return sum(a_list)

Solution 2

def sum_if_list_of_ints(a_list):
    for item in a_list:
        if not isinstance(item, int):
            break
    else:
        return sum(a_list)
    return 'not an int'

Sum if list only contains integers

Define a function sum_if_list_of_ints that receives a list and uses a loop
to make sure the list only contains integers. If so, it returns the sum of
the integers. If not, return 'not an int'.

Hint: Use isinstance again to determine the type.

Examples:

>>> sum_if_list_of_ints([1, 2, 3])
6
>>> sum_if_list_of_ints([1, 'a', 3])
'not an int'
>>> sum_if_list_of_ints([])
0

Test Cases

test empty list - Run Test

def test_empty_list():
    assert sum_if_list_of_ints([]) == 0

test sum of ints - Run Test

def test_sum_of_ints():
    assert sum_if_list_of_ints([1, 2, 3]) == 6

test mixed list - Run Test

def test_mixed_list():
    assert sum_if_list_of_ints([1, 'a', 3]) == 'not an int'
def sum_if_list_of_ints(a_list): pass