Count - code works but doesn't print


#1

Hi, just doing the count excercise and the code apparently works fine, but won't print the answer for the sequence/item I wanted to use to test it.

My code:

def count (sequence, item):
    total = 0
    for i in sequence:
        if i == item:
            total += 1
    return total
    print total

count([1, 2, 1, 1], 1)

#2

Hi this line

count([1, 2, 1, 1], 1)

just add the print before it


#3

Thanks, that works, but why does it not print from the command within the function (line 7)?


#4

I think that after the function return something it doesn't run the next line so in your function put it like that

    print total
    return total

first the print then the return statement


#5

Cheers, swapping them worked.


#6

the moment a return keyword is reached, the function ends (the rest of the function doesn't get executed). Which can be really useful as well when used correctly. (you can do, for example, error checking, and just return if something goes wrong)