CodeStart / Python Course / Lesson 14

Lesson 14: Function Exercises

Module 5: Functions · about 15 min · free

Now it's time to put what you've learned about functions into practice! Try to build these functions on your own before opening the answers.

1st Exercise: Even or Odd Checker

Write a function named is_even(number) that takes a single integer as an argument. It should return True if the number is even, and False if it is odd.

Example call: print(is_even(4)) → Output: True

Reveal Answer

def is_even(number):
    if number % 2 == 0:
        return True
    else:
        return False
a = is_even(5)
b = is_even(992)
print(a)
print(b)

Output

False
True

2nd Exercise: Calculate Average of a List

Write a function named calculate_average(numbers_list) that accepts a list of numbers as an argument and returns the average (mean) of all the numbers in that list.

Example: calculate_average([10, 20, 30, 40]) → Output: 25.0

Reveal Answer

def calculate_average(numbers_list):
    if len(numbers_list) == 0:
        return 0
    return sum(numbers_list) / len(numbers_list)
average = calculate_average([10, 20, 30, 40])
print(average)

Output

25.0

3rd Exercise: Find the Maximum Number

Write a function named find_max(a, b, c) that accepts three numbers as arguments and returns the largest of the three numbers without using Python's built-in max() function.

Reveal Answer

def find_max(a, b, c):
    if a >= b and a >= c:
        return a
    elif b >= a and b >= c:
        return b
    else:
        return c
maxNum = find_max(81, -20, 5)
print(maxNum)

Output

81

Want XP, levels and progress tracking? Play this lesson in the CodeStart game.

Play Lesson 14