Python functions are reusable blocks of code that perform specific tasks. Here's how to define them:
Basic Syntax 💡
def function_name(parameters):
# code block
return value
Parameters & Arguments 📌
- Parameters are variables listed in the function definition
- Arguments are the actual values passed when calling the function
- Default values can be set:
def greet(name="World"):
Return Values 🚀
Use return
to output results from a function.
Example:
def add(a, b):
return a + b
Example Code 📜
def calculate_area(radius):
π = 3.14159
return π * radius**2
# Calling the function
area = calculate_area(5)
print(area) # Output: 78.5395
Best Practices ✅
- Use descriptive names
- Keep functions focused on single tasks
- Include docstrings for documentation
- Handle edge cases with error checking
For more advanced topics like lambda functions or decorators, check out /en/Python/Functions/Advanced.