Python functions are blocks of reusable code designed to perform specific tasks efficiently. They help in modularity and reusability, making code structured and organized.
Python comes with ready-made functions like print(), len(), and sum() that are always available.
Additional modules in Python include math, random, and datetime, which need to be imported.
Custom functions that developers create using the def keyword.
Functions in Python start with the def keyword. Example:
def greetings():
"""This function prints a greeting message"""
print("Hello, World!")
To execute a function, use its name followed by parentheses:
greetings()
Arguments must be provided in the same order as defined.
Arguments can be passed in any order using parameter names.
Functions can have default values for arguments.
The return statement allows a function to send back a value:
def add(a, b):
return a + b
result = add(5, 10)
print(result) # Output: 15
Python allows small, anonymous functions using lambda:
sum = lambda x, y: x + y print(sum(5, 10)) # Output: 15
