Define a Function
In this chapter we'll learn how to define a function of our own.
Function definition syntax
def function_name(parameter1, parameter2, ...):
code # standard indentation of four spaces
code
Functions are defined using the def
keyword. After this keyword comes function name, followed by a pair of parentheses which may enclose some parameters. The line ends with a colon. After this line is the function body, which consists of all code that runs when this function is called. All lines in function body is indented.
The parameters (a.k.a. arguments) specify things(if any) that will be provided by the code that calls this function. The parameter list may be empty, or it may contain any number of parameters separated by commas.
Parentheses are required even if the parameter list is empty.
Python's indentation rule. All lines inside function body are indented by the same number of spaces, same as the code block in the
for
loop. One of the most distinctive features of Python is its use of indentation to mark blocks of code. We use 4 spaces to indent code blocks.
Python's compound statements Pattern:
- A header line which begins with a keyword and ends with a colon.
- A body consisting of one or more Python statements, each indented the same amount from the header line.
We’ve already seen the for
loop following this pattern, so does the if
statement that we'll learn later.
Simple functions with no input parameters
def say_hi():
print('Hi!')
The first line begins with the keyword def
to start the new function called say_hi
. The empty parenthesis means this function doesn't have any input parameters. The line ends with a colon.
The function body contains only one line and it's indented by 4 spaces.