Python Functions
Functions are blocks of reusable code in Python. They are intended to execute specific tasks. Organizing and structuring the code helps to make it modular, easier to understand, debug, and maintain. Let’s see Python functions in detail.
1. What is a Function?
A function is a named part of a program that serves a particular purpose. Functions accept input (if necessary), operate on it, and then return output (if required).
Types of Functions in Python
- Built-in Functions: Available in Python, for example,
print()
,len()
,type
. - User-defined functions: functions that you specify to execute a particular activity.
2. Defining a Function
In Python, you use the def
keyword to define a function. Here’s the syntax:
def function_name(parameters):
"""
Optional docstring to describe the function.
"""
# Function body
return result
Key Elements:
def
keyword: Keyword that marks the beginning of a function declaration.- Function Name: Identifies the function. Naming rules:
- Use lowercase letters
- Words separated by underscores, for example,
calculate_sum
.
3. Parameters (Optional): Variables taken as input by the function.
4. Function Body: The block of statements where operations are performed.
5. Return Statement (Optional): Sends back an answer to the caller.
3. Calling a Function
You invoke a function by using its name followed by parentheses. If the function requires parameters, you pass arguments inside the parentheses.
# Example of calling a function
def greet(name):
return f"Hello, {name}!"
message = greet("Alice")
print(message) # Output: Hello, Alice!
4. Parameters and Arguments
Functions can accept parameters to make them more dynamic.
Types of Parameters:
- Positional Parameters: The most common type; arguments must be passed in the same order as defined.
def add(a, b):
return a + b
print(add(3, 4)) # Output: 7
2. Default Parameters: Provide default values to parameters, making them optional.
def greet(name="User"):
return f"Hello, {name}!"
print(greet()) # Output: Hello, User!
print(greet("Alice")) # Output: Hello, Alice!
3. Keyword Arguments: Arguments passed by name, not position.
def describe_pet(animal_type, pet_name):
return f"I have a {animal_type} named {pet_name}."
print(describe_pet(pet_name="Buddy", animal_type="dog"))
# Output: I have a dog named Buddy.
4. Arbitrary Arguments: Handle variable numbers of arguments.
*args
for positional arguments.**kwargs
for keyword arguments.
def sum_all(*numbers):
return sum(numbers)
print(sum_all(1, 2, 3, 4)) # Output: 10
def print_details(**info):
for key, value in info.items():
print(f"{key}: {value}")
print_details(name="Alice", age=25, country="USA")
# Output:
# name: Alice
# age: 25
# country: USA
5. Return Statement
The return
statement sends back the result of a function. If no return
is specified, the function returns None
.
def square(number):
return number ** 2
result = square(5)
print(result) # Output: 25
6. Scope and Lifetime of Variables
- Local Scope: Variables declared inside a function are local to that function.
- Global Scope: Variables assigned outside any function are also accessible throughout the program.
- Use the
global
keyword to change the global variables within a function.
x = 10 # Global variable
def modify_global():
global x
x = 20
modify_global()
print(x) # Output: 20
7. Nested Functions
Functions can be defined inside other functions.
def outer_function(text):
def inner_function():
return text.upper()
return inner_function()
print(outer_function("hello")) # Output: HELLO
8. Lambda Functions
A lambda function is an anonymous, single-expression function defined using the lambda
keyword.
# Lambda function syntax
square = lambda x: x ** 2
print(square(5)) # Output: 25
# Lambda with multiple arguments
add = lambda a, b: a + b
print(add(3, 4)) # Output: 7
9. Examples of Functions
Example 1: Function to Find Factorial
def factorial(n):
if n == 0 or n == 1:
return 1
else:
return n * factorial(n - 1)
print(factorial(5)) # Output: 120
Example 2: Function with Default and Keyword Arguments
def introduce(name, age=30, country="USA"):
return f"My name is {name}, I am {age} years old, and I live in {country}."
print(introduce("Alice")) # Output: My name is Alice, I am 30 years old, and I live in USA.
print(introduce("Bob", 25, "Canada")) # Output: My name is Bob, I am 25 years old, and I live in Canada.
10. Best Practices
- Use meaningful function names.
- Keep the function small and focused to one task.
- Write clear docstrings for clarity and documentation.
- Avoid global variables when possible.
- Test the function carefully.