Pulsars
0 %
Log inSign up

Breaking Your Code into Functions

Defining a Function with def

Defining a Function with def

In Python, you define a function with the keyword def, followed by the function name, parentheses, and then a colon:

def say_hello():
    print("Hello!")

This function is called say_hello. The code indented under the def line (here, the line print("Hello!")) makes up the body of the function: this is what runs each time it is called.

Watch out: writing this definition doesn't execute anything at all! A function only runs when you call it, that is, when you write its name followed by parentheses:

def say_hello():
    print("Hello!")

say_hello()   # (this prints Hello! the first time)
say_hello()   # (this prints Hello! a second time)

You can call the same function as many times as you want: that's the whole point of reusability.

A function's name follows the same rules as a variable's: no spaces, no accents, and an explicit name that describes what the function does, usually with a verb (calculate_..., display_..., check_...).

Common mistake: forgetting the colon : at the end of the def line, or forgetting to indent the function's body. In Python, indentation isn't a matter of style: it's what indicates where the function's body starts and ends. An improperly indented line is no longer part of the function.