Skip to Main Content
It looks like you're using Internet Explorer 11 or older. This website works best with modern browsers such as the latest versions of Chrome, Firefox, Safari, and Edge. If you continue with this browser, you may see unexpected results.

Python for Basic Data Analysis: 2.9 Functions - More Exercises

Get started on your learning journey towards data science using Python. Equip yourself with practical skills in Python programming for the purpose of basic data manipulation and analysis.

Try It Yourself!

Here are some function exercises for you to apply what you have just learnt.

Templates for the answers have been given so just add on to it! If you don't want to use it that fine too. There are many ways you can write a function to do the same thing.

Have fun! 

Activity 1

You have 103 apples and would like to share them with 5 people. Write a function to find the remainder. Hints: 5 % 4 gives remainder when 5 divided by 4

def remaining(total_apples,num_people):
    """return the remaining number of apples after dividing equally"""
    return

Activity 2

Write a recursive function that will return the nth term of the Fibonacci sequence.

The sequence has a relationship of Fn = Fn-1 + Fn-2 with F0 = 0 and F1 = 1, where n=0,1,2,3,4,5,...

The sequence looks like: 0,1,1,2,3,5,8,13,...

 

def fibonaci(n):
    """return the full fibonaci sequence"""
    if n == 0:
        return 0

    elif n == 1:
        return 1

 

Activity 3

Write a function that will count how many odd numbers is present in a given list of integers. 

Fill in the function below.

Hint: Use this list to check your function
[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]

 

def count_odd_numbers(numbers):

    count = 0
    for i in ____:
        if ____ % 2 == _____:
            count += ____

    return ____

Activity 4

Write a lambda expression that will cube all the numbers in the list below

num = [1,2,3,4,5,6,7,8]