Python Functions · Exercises
Core Python

Python Functions Exercises

4 exercises that build on the Python Functions lesson, from easy to hard. Each one is checked in your browser when you press Check. Stuck? Use the hint before peeking at the solution.

What this lesson covers: A function is a named, reusable block of code that takes inputs (arguments), does some work, and can hand a result back with return. By the end you can define and call your own functions, tell parameters from arguments, return values instead of printing them, and use default values, keyword arguments and docstrings. You will practise: Write a square function; Predict the calls; Fix the discount function; Count words with a default length.

0 / 4 completed

Python Functions practice exercises

1. Write a square function

Write code Easy

Complete the function square(n) so that it returns n multiplied by itself. For example, square(4) returns 16.

Your code
def square(n):
    # return n multiplied by itself
    pass


print(square(4))

2. Predict the calls

Predict the output Medium

Read the code and type exactly what it will print. Then press Check to run it and compare.

Read this code
def add(a, b=10):
    print("adding", a, b)
    return a + b

x = add(1)
y = add(1, 2)
print(x, y)
print(add(b=1, a=5) * 2)

3. Fix the discount function

Fix the bug Medium

apply_discount(price, percent) should return the reduced price, so that the program prints Sale price: 60.0. Right now it prints Sale price: None. Fix the function.

Your code
def apply_discount(price, percent):
    new_price = price - price * percent / 100
    print(new_price)

sale = apply_discount(80, 25)
print("Sale price:", sale)

4. Count words with a default length

Write code Hard

Define a function count_words(text, min_length=1) with a docstring. It returns how many words in text have at least min_length characters. Words are separated by spaces (use text.split()).

  • count_words("the quick brown fox") returns 4
  • count_words("the quick brown fox", min_length=4) returns 2
Your code
# Define count_words(text, min_length=1) here


print(count_words("the quick brown fox"))
print(count_words("the quick brown fox", min_length=4))

Next lessonPython Function Arguments

More Python Functions examples · All Python exercises