Python Functions
Functions are organized, reusable code segments that implement single or related functions. Functions improve the modularity of applications and code reuse. You have already used many built-in functions like print() and len(), and now you will learn how to create your own functions.
Defining Functions
- The function code block starts with the
defkeyword, followed by the function name and parentheses(). - Any arguments and variables passed in must be placed between the parentheses.
- The first line of the function can optionally use a docstring (document string) to add a description to the function.
- The function body starts with a colon
:and is indented. return [expression]ends the function and optionally returns a value to the caller. Areturnstatement without an expression is equivalent to returningNone.
Basic Syntax:
Calling Functions
Defining a function only gives the function a name, specifies the parameters contained in the function, and the code block structure. After completing this basic structure of the function, you can execute it by calling from another function, or directly from the Python command prompt.
Parameters
Functions can receive parameters, which are values passed to the function for internal use.
Positional Parameters
When calling a function, the passed values are assigned to parameters in order.
Keyword Parameters
You can also use key=value form to pass parameters, allowing you to ignore parameter order.
Default Parameters
When defining a function, you can specify a default value for a parameter. If the function is called without providing a value for that parameter, the default value will be used.
Return Values
Functions can use the return statement to return a value to the caller. A function can return any type of value, including complex structures like lists and dictionaries.
A function can have no return statement, or return followed by no value. In this case, the function automatically returns None.
Returning Multiple Values
A function can return multiple values at once; these values will be packaged as a tuple.
Variable Scope
- Local Variables: Variables defined inside a function can only be accessed within that function.
- Global Variables: Variables defined outside a function can be accessed anywhere in the program (including inside functions).