A function is a block of organized, reusable code that is used to perform a single, related action. Functions provide better modularity for your application and a high degree of code reusing.
In Python, we use the def keyword to define a function.
1. The Structure of a Function
Definition: Starts with
def, followed by the function name and parentheses().Parameters: Inputs to the function placed inside the parentheses.
Body: The indented code that executes when the function is called.
Return: The
returnstatement sends a result back to the caller. If no return is specified, the function returnsNone.
2. Arguments: Positional, Keyword, and Default
Python offers great flexibility in how you pass data to functions:
Positional: Arguments passed in the correct order.
Default: You can assign a value to a parameter in the definition so it's optional during the call.
Keyword: You can pass arguments by name, so the order doesn't matter.
# Function with a default parameter
def greet(name, message="Welcome to the team!"):
return f"Hello {name}, {message}"
# 1. Calling with both arguments (Positional)
print(greet("Alice", "Good Morning!"))
# 2. Calling with only the required argument (Using Default)
print(greet("Bob"))
# 3. Calling with Keyword arguments (Order changed)
print(greet(message="How are you?", name="Charlie"))
# Function to calculate area
def calculate_area(length, width):
area = length * width
return area
result = calculate_area(5, 10)
print(f"Area: {result}")3. Scope of Variables
Local Scope: Variables created inside a function belong to that function and cannot be accessed outside.
Global Scope: Variables created in the main body of the script are accessible everywhere.