Python Functions
In Python, a function is a block of organized, reusable code that performs a specific task. Functions provide modularity and allow you to break down your program into smaller, manageable pieces. Here is the basic syntax for defining and calling a function:
Defining a Function:
def function_name(parameters):
# Code to be executed
return result # Optional
def
: Keyword used to define a function.function_name
: Name of the function.parameters
: Input values that the function accepts (optional).return
: Keyword used to specify the return value of the function (optional).
Example of a Simple Function:
def greet(name):
"""This function greets the person passed in as a parameter."""
print(f"Hello, {name}!")
# Calling the function
greet("Alice")
greet("Bob")
In this example, greet
is a function that takes a parameter name
and prints a greeting message.
Function with Return Value:
def add(x, y):
"""This function adds two numbers and returns the result."""
result = x + y
return result
# Calling the function
sum_result = add(3, 4)
print(f"The sum is: {sum_result}")
The add
function takes two parameters (x
and y
), adds them, and returns the result.
Default Parameter Values:
def power(base, exponent=2):
"""This function calculates the power of a number with an optional exponent."""
result = base ** exponent
return result
# Calling the function with and without specifying the exponent
print(power(3)) # Uses default exponent (2)
print(power(3, 3)) # Specifies exponent as 3
The power
function has a default value for the exponent
parameter, allowing the function to be called with or without specifying the exponent.
Variable Number of Arguments:
def print_arguments(*args):
"""This function prints all the arguments passed to it."""
for arg in args:
print(arg)
# Calling the function with multiple arguments
print_arguments(1, "hello", [3, 4])
The *args
syntax allows a function to accept a variable number of positional arguments.
Keyword Arguments:
def greet_person(name, greeting="Hello", punctuation="!"):
"""This function greets a person with customizable greeting and punctuation."""
print(f"{greeting}, {name}{punctuation}")
# Calling the function with keyword arguments
greet_person("Alice", greeting="Hi", punctuation="!!!")
Keyword arguments allow you to specify values for parameters by name when calling the function.
Lambda Functions (Anonymous Functions):
multiply = lambda x, y: x * y
print(multiply(3, 4))
Lambda functions are concise, one-line functions defined using the lambda
keyword.
These examples cover the basics of defining, calling, and customizing functions in Python. Functions are essential for creating reusable and organized code in your programs.