Use the def keyword to define a function.
def function_name(parameter1, parameter2="default_value", *args, **kwargs):
# Code block inside the function
statement_a
statement_b
# ...
# Optional: return value
# return result
def: Keyword to start a function definition.function_name: A descriptive name for the function.(parameter1, parameter2="default_value", ...): Optional list of parameters.
=. Parameters with default values must come after parameters without default values.args: Gathers any extra positional arguments into a tuple.*kwargs: Gathers any extra keyword arguments into a dictionary.:: Marks the end of the function header.To execute the code inside a function, you call it by its name followed by parentheses (). If the function expects parameters, you provide arguments.
# Calling a function with no parameters
function_name()
# Calling a function with positional arguments
function_name(argument1, argument2)
# Calling a function using keyword arguments (order doesn't matter)
function_name(parameter2=argument2, parameter1=argument1)
function_name(parameter1=value1) # Using default for parameter2
# Mixing positional and keyword arguments (positional must come first)
function_name(argument1, parameter2=argument2)
# Calling a function that returns a value
result = function_name(argument1)
argument1, argument2: The actual values passed to the function's parameters.=. This allows you to pass arguments in any order and makes the call clearer.return StatementUsed inside a function to exit the function and optionally send a value back to the caller.
def add_numbers(a, b):
sum_result = a + b
return sum_result # Return the calculated sum
# Call the function and store the returned value
total = add_numbers(5, 3) # total will be 8
return: Keyword to exit the function.