Python Functions
$count++; if($count == 1) { include "../mobilemenu.php"; } ?> if ($count == 2) { include "../sharemediasubfolder.php"; } ?>
Functions in Python allow us to encapsulate reusable code. A function is a block of code that only runs when it is called. Functions are defined using the `def` keyword, can take parameters, return values, and can be either built-in or user-defined. Here, we'll explore function creation, arguments, return values, lambda functions, and other important concepts related to Python functions.
1. Defining and Calling a Function
To define a function, use the `def` keyword, followed by the function name and parentheses `()`. The function body is indented.# Define a simple function
def greet():
print("Hello, world!")
# Call the function
greet()
Output:
Hello, world!
2. Function with Parameters
Functions can accept parameters, which allow you to pass data into the function.# Function with parameters
def greet(name):
print(f"Hello, {name}!")
# Call the function with an argument
greet("Alice")
Output:
Hello, Alice!
3. Function with Default Parameters
You can assign default values to parameters. If a value isn’t provided, the default is used.# Function with a default parameter
def greet(name="Stranger"):
print(f"Hello, {name}!")
# Call the function without and with an argument
greet()
greet("Bob")
Output:
Hello, Stranger!
Hello, Bob!
4. Function with Multiple Parameters
A function can accept multiple parameters, allowing you to pass multiple arguments when calling it.# Function with multiple parameters
def add(a, b):
return a + b
# Call the function with two arguments
result = add(3, 5)
print("Sum:", result)
Output:
Sum: 8
5. Return Values
Functions can return values using the `return` keyword, which allows you to use the function’s result elsewhere in your code.# Function that returns a value
def square(num):
return num * num
# Use the returned value
result = square(4)
print("Square:", result)
Output:
Square: 16
6. Keyword Arguments
Python allows you to specify arguments by their parameter name, which can improve readability and allows arguments to be passed in any order.# Function with keyword arguments
def introduce(name, age):
print(f"My name is {name} and I am {age} years old.")
# Call function with keyword arguments
introduce(age=25, name="Alice")
Output:
My name is Alice and I am 25 years old.
7. Arbitrary Arguments (`*args`)
The `*args` syntax allows a function to accept a variable number of positional arguments, which are accessible as a tuple.# Function with *args
def list_numbers(*args):
print("Numbers:", args)
# Call the function with multiple arguments
list_numbers(1, 2, 3, 4, 5)
Output:
Numbers: (1, 2, 3, 4, 5)
8. Arbitrary Keyword Arguments (`**kwargs`)
The `**kwargs` syntax allows a function to accept a variable number of keyword arguments, accessible as a dictionary.# Function with **kwargs
def display_info(**kwargs):
print("Info:", kwargs)
# Call the function with multiple keyword arguments
display_info(name="Alice", age=30, country="USA")
Output:
Info: {'name': 'Alice', 'age': 30, 'country': 'USA'}
9. Lambda Functions
Lambda functions are small, anonymous functions defined with the `lambda` keyword. They’re often used for short, simple operations.# Lambda function to add two numbers
add = lambda x, y: x + y
# Use the lambda function
result = add(3, 7)
print("Lambda Add Result:", result)
Output:
Lambda Add Result: 10
10. Nested Functions
Functions can be nested within other functions. A nested function has access to the outer function's variables.def outer_function(text):
def inner_function():
print(text)
inner_function()
outer_function("Hello from inner function")
Output:
Hello from inner function
11. Function as Arguments
In Python, functions are first-class objects, meaning they can be passed as arguments to other functions.def shout(text):
return text.upper()
def whisper(text):
return text.lower()
def greet(func, message):
print(func(message))
greet(shout, "Hello")
greet(whisper, "Hello")
Output:
HELLO
hello
12. Recursion
A function can call itself, a process known as recursion. Recursive functions are useful for solving problems that can be divided into similar subproblems.# Recursive function to calculate factorial
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n - 1)
print("Factorial of 5:", factorial(5))
Output:
Factorial of 5: 120
13. Docstrings
Docstrings are documentation strings used to describe what a function does. They are written as the first statement in a function body and are accessible via `__doc__`.def greet():
"""This function greets the user."""
print("Hello!")
print(greet.__doc__)
Output:
This function greets the user.
Summary
Python functions are versatile, supporting features like parameters, return values, lambda expressions, nested functions, recursion, and more. Functions enable reusable, modular, and readable code, which is a core practice for efficient programming.