A basic function definition in Python requires the following:
defis followed by the function’s name. The name,
fooin this example, is chosen by the programmer to reflect what the function does.
def foo(): x = 1 y = 2
Functions can be called to return values which may be used as variables, within expressions, or to be fed into other functions. The
return keyword ends a function and returns a value to the caller. If no value is given, the value
None is returned.
def get_president(): return 'Billy Kangaroo' print(get_president())
The above example will print the string
Billy Kangaroo. The
print() function calls
get_president() which returns the value
Billy Kangaroo. This string is then used by the
print() function to print to the console.
def get_president(): return print(get_president())
Removing the return value will print
None as the function
get_president() no longer returns the string. Additionally, removing the
return and replacing it with some other code will create an implicit
return with value
External values may be passed to functions for use within them. These values may be provided as variables, literals or expressions in a comma-separated list within the function parentheses. See the following example.
>>> def square(num): ... return num ** 2 >>> square(5) 25
square() function is called with the value
5 given in parentheses. In
def square(num), the keyword
num points to the value given by the caller which can be used within the function. In the case of
num will retrieve
square() function is therefore able to be used to square any given number.