Functions
In programming, a function is a reusable block of code that executes a certain functionality when it is called.They play a vital role in modularizing code, improving readability, and promoting code reusability. This tutorial provides an overview of Python functions, including their creation, parameters, return values, and usage.
Creating a Function
You can create a function in Python using the def keyword,
followed by the function name and a pair of parentheses ().
The function body is indented below the function definition.
def greet():
print("Hello, World!")
Function Parameters
Functions can take input values known as parameters or arguments, allowing you to customize their behavior based on the input.
def greet_user(username):
print(f"Hello, {username}!")
Function Invocation
To execute a function, you need to call it by its name, followed by a
pair of parentheses ().
# Calling the function without parameters
greet()
# Calling the function with a parameter
greet_user("Alice")
Return Values
Functions can return values using the return statement. The returned value can be assigned to a variable or used directly.
def add_numbers(a, b):
# Function to add two numbers
return a + b
# Calling the function and storing the result in a variable
result = add_numbers(10, 5)
print(result) # Output: 15
# Using the function directly in an expression
sum_result = add_numbers(3, 7) + add_numbers(2, 8)
print(sum_result) # Output: 20
Default Parameters
You can provide default values for parameters in a function. If a value is not passed for that parameter during the function call, the default value is used.
def greet_user(username="Guest"):
print(f"Hello, {username}!")
# Calling the function without passing a value
greet_user() # Output: Hello, Guest!
# Calling the function with a custom value
greet_user("Alice") # Output: Hello, Alice!
Variable-Length Arguments
Python allows you to define functions that can accept a variable number
of arguments using *args (for non-keyword arguments) and
**kwargs (for keyword arguments).
def add_all_numbers(*args):
# Function to add all numbers passed as arguments
total = 0
for num in args:
total += num
return total
# Calling the function with different numbers of arguments
result1 = add_all_numbers(1, 2, 3, 4)
result2 = add_all_numbers(10, 20, 30, 40, 50)
print(result1) # Output: 10
print(result2) # Output: 150
Lambda Functions
Lambda functions are small, anonymous functions defined using the
lambda keyword.
# Regular function to square a number
def square(x):
return x ** 2
# Equivalent lambda function
square_lambda = lambda x: x ** 2
# Using the lambda function
print(square_lambda(5)) # Output: 25