Functions in Python
Functions are reusable blocks of code that allow you to structure programs efficiently. They can accept parameters, return values, and can be customized in countless ways.
Defining functions
def greet():
print("Hello, John!")
Parameters and return values
def add(a, b):
return a + b
result = add(3, 5)
print(result) # Prints: 8
Default arguments and *args - **kwargs
def greet(name="Anonymous"):
print(f"Hello, {name}!")
greet() # Hello, Anonymous!
greet("John") # Hello, John!
def total(*numbers):
return sum(numbers)
print(total(1, 2, 3)) # Prints: 6
def details(**info):
print(info)
details(name="John", age=30)
Docstrings and comments
def multiply(a, b):
"""Returns the product of two numbers."""
return a * b
# Simple comment
# This function multiplies two values
Lambda functions
square = lambda x: x * x
print(square(4)) # Prints: 16
Useful built-in functions
print(len("Python")) # 6
print(sum([1, 2, 3])) # 6
print(range(5)) # range(0, 5)
Recursion
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n - 1)
print(factorial(5)) # Prints: 120
- Functions can be documented with
"""docstring"""for clarity. - Arguments
*argsand**kwargsprovide flexibility in calls. - Lambda functions are useful for short expressions but do not replace classic functions.
- Recursion should be used carefully โ it can lead to stack overflow errors.
