In Python, a function is a block of code that performs a specific task. It can accept input values, called arguments or parameters, and return output values. Functions are used to break down a program into smaller, manageable parts, making it easier to understand, debug, and reuse code.
sparkdatabox providing python training in Coimbatore with 100% placement assurance
example of a simple function in Python:
In this example, the greet()
function takes a single parameter name
and prints out a greeting message that includes the name. The function is defined using the def
keyword followed by the function name and its parameters in parentheses. The code inside the function is indented and executed when the function is called.
To call the greet()
function, we simply pass in a value for the name
parameter. In this case, we pass in the string “John”. The output of the program will be:
Functions can also return values using the return
keyword. Here’s an example:
Addition of two numbers in python using function
In this example, the add_numbers()
function takes two parameters x
and y
, adds them together, and returns the result using the return
keyword. We call the function and store the result in a variable sum
. Finally, we print out the result using the print()
function.