Functions
9 min · Python
Package code under a name so you can reuse it.
Enemy 1 of 5
A function is a named, reusable block of code — write the logic once, then run it as many times as you want just by calling its name. Functions are how programmers avoid repeating themselves: instead of copy-pasting five lines every time you need to do a task, you wrap those five lines in a function and call it wherever needed.
You define a function with def, followed by a name and parentheses, then a colon, then an indented body — the same indentation rule from if statements applies here too. Crucially, defining a function does not run its body; Python just remembers the recipe. Nothing actually happens until you call the function by name followed by parentheses, e.g. greet().
Run this — defining greet prints nothing; calling greet() is what runs it. If you comment out the last line, the program produces no output at all, even though the function definition is still there.
Loading editor...