Define a function that takes arguments and returns a value, and show what a function with no return statement gives back.
A function is defined with the def keyword, followed by a name, a list of parameters in parentheses, and a colon. The body of the function is indented underneath it.
def greet(name, greeting='Hello'):
return greeting + ', ' + name + '!'
print(greet('Ada')) # Hello, Ada!
print(greet('Ada', greeting='Hi')) # Hi, Ada!
def no_return(value):
print('inside:', value)
result = no_return(42)
print('returned:', result) # returned: None
The first function takes one required parameter and one that has a default value. The second function prints something and returns nothing, so the assignment binds the result to None. That is the most common surprise for newcomers, because a function that forgets to return quietly produces None instead of raising an error.
Two details about the definition itself are worth knowing. The def statement does not run the body. It creates a function object and binds the name to it, so you may define a function after another function that calls it, as long as the call happens after the definition has run. And the body of a function cannot see the local variables of the caller, which is one of the things that keeps functions easy to test.
The def keyword and the parentheses are both required by the grammar, unlike some languages where a function without parameters can be written without them. The structure also makes the return value obvious, because everything after return is a single expression. You cannot return two statements, but you can return two values inside one tuple.