In Python, functions are defined using the def keyword followed by the function name and parentheses containing any parameters. The function body is indented and contains the code that will be executed when the function is called. 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):
result = a + b
return result
Key Points:
- Function Name: Should be descriptive and follow naming conventions (e.g., lowercase with underscores).
- Parameters: Optional; you can define functions with or without parameters.
- Return Statement: Used to return a value from the function. If omitted, the function returns
None.
Calling a Function:
To use the function, you simply call it by its name and pass the required arguments:
sum = add_numbers(3, 5)
print(sum) # Output: 8
This structure allows for code reuse and modular programming in Python. If you have more questions about functions or need examples, feel free to ask!
