Home › Learn › Python › Making decisions

Functions

Lesson 9 of 40. Package code under a name, give it inputs, get a result back.

def name(parameters): starts a function; the indented body runs each time you call name(arguments). return value hands a result back to the caller and ends the function. A function with no return gives back None.

Returning is different from printing. print shows something to a person; return gives the value to the code that called the function, which can store it, compare it, or pass it on. The checks in these lessons call your functions and look at what comes back, so return, do not print.

A string on the first line of the body is a docstring, a description that tools and help() show. Short functions with clear names and one job are the goal.

def circle_area(radius):
    """Area of a circle with the given radius."""
    return 3.14159 * radius ** 2

big = circle_area(10)
print(big > 300)

Your task

Write rectangle_area(width, height) that returns the area, and word_kind(word) that returns "short" for a word of up to 3 characters, "medium" for 4 to 6, and "long" for 7 or more.

Part of the final project. word_kind sorts a word into short, medium, or long, so the report can count each kind. It is saved in this browser and loaded into Project: text statistics when you get there.

Hint 1

return width * height

Hint 2

if len(word) <= 3: return "short", then elif len(word) <= 6, then else. A return ends the function, so the later branches only run when the earlier ones did not.

Show the solution
def rectangle_area(width, height):
    return width * height


def word_kind(word):
    if len(word) <= 3:
        return "short"
    elif len(word) <= 6:
        return "medium"
    else:
        return "long"

    Runs CPython compiled to WebAssembly in this tab (12 MB download the first time, then cached); nothing is sent anywhere.