List + Functions example


#1


The following code is from List + Functions and it's the example and the result comes out to 2. I don't understand how it came with result 2. Someone please explain. Thanks!

def count_small(numbers):
    total = 0
    for n in numbers:
        if n < 10:
            total = total + 1
    return total

lost = [4, 8, 15, 16, 23, 42]
small = count_small(lost)
print small


#2

Lets break this code in small parts and understand it..

Part 1

def count_small(numbers):
    total = 0
    for n in numbers:
        if n < 10:
            total = total + 1
    return tota

Explanation of above code...
1. We've defined a function count_small that takes list as parameter (i.e is numbers)
2.We've defined a local variable total that is set to 0.
3. We started looping over our list numbers using iteration variable n.
4. Inside the loop...
A. if a number is less than 10 then add 1 to total, keep doing this until loop iteration gets finished.
5. return the total (which will return total count of numbers that're less than 10)

So our function takes a list and counts all the numbers less than 10 and gives us count of numbers that are less than 10.

Part 2

lost = [4, 8, 15, 16, 23, 42]
small = count_small(lost)
print small

1.We've defined a list named lost .
2.we called (calling the function) count_small function and give it list lost as argument. It will return total count of numbers less than 10 and we save it in variable small
3.We print this value, that is 2.


#3

Oh I get it! Thank you!


#4

Good work :open_mouth:


#5

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.