Python

Important Statements

Defining a Function

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

Calling a Function

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)

The return Statement

Used 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