Functions in Python are blocks of reusable code designed to perform a specific task. They allow you to break down your program into smaller, more manageable pieces, promoting code organization, reusability, and readability. In Python, defining and using functions is straightforward.
Defining a Function:
You can define a function using the def
keyword, followed by the function name and a set of parentheses. Parameters (if any) are specified inside the parentheses, and the function body is indented.
def greet(name):
"""This function greets the person passed in as a parameter."""
print(f"Hello, {name}!")
# Calling the function
greet("John")
In this example, greet
is a simple function that takes a parameter name
and prints a greeting.
Function Parameters:
Functions can have parameters, which are values passed to the function when it’s called.
def add_numbers(x, y):
"""This function adds two numbers."""
return x + y
result = add_numbers(3, 7)
print(result)
The add_numbers
function takes two parameters (x
and y
) and returns their sum.
Default Parameters:
You can assign default values to parameters in a function. If a value is not provided when the function is called, the default value is used.
def power(base, exponent=2):
"""This function raises the base to the power of the exponent."""
return base ** exponent
result1 = power(2) # Uses the default exponent (2)
result2 = power(2, 3) # Uses the provided exponent (3)
print(result1) # Output: 4
print(result2) # Output: 8
In this example, the power
function has a default exponent value of 2.
Return Statement:
Functions can use the return
statement to send a result back to the caller.
def square(x):
"""This function returns the square of a number."""
return x ** 2
result = square(5)
print(result) # Output: 25
Docstrings:
Docstrings are triple-quoted strings that provide documentation for a function. They are placed immediately after the function definition and describe the purpose of the function.
def multiply(a, b):
"""This function multiplies two numbers.
Parameters:
a (int): The first number.
b (int): The second number.
Returns:
int: The product of a and b.
"""
return a * b
Scope of Variables:
Variables defined inside a function are local to that function, and they are not accessible outside of it.
def example_function():
x = 10
print(x)
example_function()
# print(x) # This would result in an error because x is not defined in this scope
Function Call with Keyword Arguments:
When calling a function, you can use keyword arguments to specify the values for parameters by their names.
def display_info(name, age):
print(f"Name: {name}, Age: {age}")
# Calling the function with keyword arguments
display_info(age=25, name="John")
Lambda Functions:
Lambda functions, or anonymous functions, are concise functions defined using the lambda
keyword.
multiply = lambda x, y: x * y
result = multiply(3, 4)
print(result) # Output: 12
Lambda functions are often used for short-term operations.
Understanding how to define, use, and work with functions is a crucial aspect of Python programming. Functions allow you to create modular and reusable code, making your programs more organized and maintainable.