Python functions allow for reusable code through defining functions, passing arguments, returning values, and setting scopes. Functions can take positional or keyword arguments, as well as variable length arguments. Default arguments allow functions to specify default values for optional parameters. Functions are objects that can be assigned to variables and referenced later.
Report
Share
Report
Share
1 of 21
More Related Content
Python Functions
1. Python Functions
● Define functions
● Passing arguments to Function
● Return a value from function
● Scope of Objects
● Default arguments
● Positional and keyword arguments
● Variable length arguments
2. Functions
Piece of reusable code
Solves particular task
Call function instead of writing code
yourself
6. Function Call
Once we have defined a function, we can call it
from another function, program or even the Python
prompt.
To call a function we simply type the function name
with appropriate parameters.
Calling the Function
my_function()
10. Scope and Lifetime of
variables
Scope of a variable is the portion of a program where the
variable is recognized.
Parameters and variables defined inside a function is not visible
from outside. Hence, they have a local scope.
Lifetime of a variable is the period throughout which the variable
exits in the memory. The lifetime of variables inside a function is
as long as the function executes.
They are destroyed once we return from the function. Hence, a
function does not remember the value of a variable from its
previous calls.
14. Default Arguments
Function arguments can have default values in
Python.
We can provide a default value to an argument by
using the assignment operator (=).
15. Default Arguments
In this function, the
parameter amount does not have a default
value and is required (mandatory) during a
call.
On the other hand, the parameter
discountPercentage has a default value
of 0. So, it is optional during a call.
If a value is provided, it will overwrite the
default value.
Any number of arguments in a function can
have a default value.
16. Default Arguments
Once we have a default argument, all
the arguments to its right must also
have default values.
SyntaxError: non-default argument
follows default argument
20. Functions as Objects
● Although functions are created differently from normal
variables, functions are just like any other kind of value.
● They can be assigned and reassigned to variables, and later
referenced by those names.