Functions within Functions - Callback Functions
A callback
function is a function that is passed as a parameter
to another function and is invoked within that function.
Callbacks are useful for executing additional actions when certain conditions are met or for processing follow-up tasks after data is ready.
How to Use Callback Functions?
Callback functions are passed as parameters to other functions, which then invoke them to dynamically execute various operations.
Callback Function Example
# Define callback functions
def add_one(number):
return number + 1
def multiply_by_two(number):
return number * 2
# Function that accepts a callback function as an argument
def process_number(number, callback):
result = callback(number)
print(f"Processed Result: {result}")
# Process with add_one function, prints 11
process_number(10, add_one)
# Process with multiply_by_two function, prints 20
process_number(10, multiply_by_two)
Want to learn more?
Join CodeFriends Plus membership or enroll in a course to start your journey.