Reusable programs · 10 min

Write a function

Give a block of code a name, inputs, and a return value.

Use def to define a function. A parameter is a name inside its definition. An argument is the value you supply when you call it. The function body runs only when called.

The return statement sends a value back to the caller and ends the function. Returning a result lets other code use it. Printing inside the function displays a message, and a function that reaches the end without returning gives back None.

Follow the example

The caller supplies two arguments.

Try it yourself

Define a perimeter function that takes width and height. Print the perimeter of a rectangle with sides 4 and 5.

Target output

18
Show a hint

Add the two sides and multiply by 2. Return the value from the function.

Output

Ready

Run your code to see the output here.

The first run downloads Python. Code runs in your browser. Progress and drafts are stored on this device.

Show one solution
def perimeter(width, height):
    return 2 * (width + height)

print(perimeter(4, 5))