How do you write a function in Python?
Ask by ICSM Computer
Updated 30 Mar 2025
The Python language defines functions through the def keyword that introduces the function name and parameter parentheses together with a colon. Inside the body of the function there is a return statement to return a result while indentation represents the code structure. Functions serve as organizing elements for code while providing reusable functions that minimize duplicated code.
A basic numerical addition function is demonstrated as follows
The function
add_numbersaccepts two parameters (a and b) to perform the calculation before returning the sum. The program invokes the function with parameters 5 and 3 while displaying the output.Python functions allow default parameters together with variable argument syntax using
argsandkwargs,and they can also be lambda expressions (single-line anonymous functions). Applicable functions enable efficient modular organization of code, which enables multiple reuse of logic segments from different places in the program.