All lessons

Functions

9 min · Python

Package code under a name so you can reuse it.

A function is a named block of code you can run whenever you want. You define it with def, give it a name, and indent the body. Nothing runs until you call it by name with ().

Run this — defining greet prints nothing; calling greet() is what runs it.

Try it yourself

Loading editor...

Ln 1, Col 1Spaces: 4
Sign up to run itExpected output: Hello!

Inputs (parameters)

A function gets more useful when you pass it values. The names in the parentheses are parameters — the function uses them like variables.

Try it yourself

Loading editor...

Ln 1, Col 1Spaces: 4
Sign up to run itExpected output: Hello, Ada!

Outputs (return)

Instead of printing, a function can return a value — hand a result back to whoever called it, so you can store or reuse it.

Try it yourself

Loading editor...

Ln 1, Col 1Spaces: 4
Sign up to run itExpected output: 10

Your turn

Write a function called square that returns its argument times itself, then print square(6) — it should be 36.

Your turn

Loading editor...

Ln 1, Col 1Spaces: 4