To define a function in Python, you use the def keyword followed by the function name and parentheses containing any parameters. Here's the basic syntax:
def function_name(parameters):
# Function body
# Code to execute
return value # Optional
Example
Here's a simple example of a function that adds two numbers:
def add_numbers(a, b):
return a + b
Explanation:
def: This keyword starts the function definition.add_numbers: This is the name of the function.(a, b): These are parameters that the function takes as input.- Function Body: The code inside the function that performs the operation.
return: This keyword sends back a value from the function.
Calling the Function
You can call the function like this:
result = add_numbers(3, 5)
print(result) # Output: 8
Feel free to ask if you need more examples or explanations!
