Python Functions
Functions are one of the fundamental building blocks in Python programming. They allow you to organize your code into reusable blocks, making your programs more modular, maintainable, and readable. Understanding functions is essential before diving into data manipulation with libraries like Pandas.
What is a Function?
A function is a block of organized, reusable code that performs a specific task. Think of functions as mini-programs within your program. They help break down complex problems into smaller, manageable pieces.
Why Use Functions?
- Reusability: Write code once and use it multiple times
- Organization: Structure your code into logical segments
- Maintainability: Easier to debug and update
- Abstraction: Hide complex implementations behind simple interfaces
Defining Functions in Python
In Python, functions are defined using the def
keyword, followed by the function name and parentheses.
Basic Function Syntax
def function_name(parameters):
"""Docstring - explains what the function does"""
# Function body - code that runs when the function is called
return value # Optional return statement
A Simple Function Example
def greet():
"""This function prints a greeting message."""
print("Hello, welcome to Python functions!")
# Calling the function
greet()
Output:
Hello, welcome to Python functions!
Function Parameters and Arguments
Parameters allow functions to accept input values, making them more flexible and powerful.
Function with Parameters
def greet_person(name):
"""Greet a specific person."""
print(f"Hello, {name}! Welcome to Python functions!")
# Calling the function with an argument
greet_person("Alex")
greet_person("Sam")
Output:
Hello, Alex! Welcome to Python functions!
Hello, Sam! Welcome to Python functions!
Multiple Parameters
def add_numbers(a, b):
"""Add two numbers and return the result."""
sum_result = a + b
return sum_result
# Call the function and store the result
result = add_numbers(5, 3)
print(f"The sum is: {result}")
# Or directly use the result
print(f"10 + 20 = {add_numbers(10, 20)}")
Output:
The sum is: 8
10 + 20 = 30
Return Values
Functions can return values using the return
statement. A function can return a single value, multiple values, or nothing at all.
Returning Single Value
def square(number):
"""Return the square of a number."""
return number * number
result = square(4)
print(f"The square of 4 is {result}")
Output:
The square of 4 is 16
Returning Multiple Values
def calculate_stats(numbers):
"""Calculate the sum and average of a list of numbers."""
total = sum(numbers)
average = total / len(numbers)
return total, average
my_numbers = [10, 20, 30, 40, 50]
sum_result, avg_result = calculate_stats(my_numbers)
print(f"Sum: {sum_result}, Average: {avg_result}")
Output:
Sum: 150, Average: 30.0
Default Parameter Values
You can assign default values to parameters, making them optional when calling the function.
def greet_with_title(name, title="Mr./Ms."):
"""Greet a person with their title."""
print(f"Hello, {title} {name}!")
greet_with_title("Johnson") # Uses default title
greet_with_title("Smith", "Dr.") # Uses provided title
Output:
Hello, Mr./Ms. Johnson!
Hello, Dr. Smith!
Keyword Arguments
You can use parameter names to specify which argument goes with which parameter, regardless of order.
def describe_pet(pet_name, animal_type):
"""Display information about a pet."""
print(f"I have a {animal_type} named {pet_name}.")
# Using keyword arguments
describe_pet(animal_type="hamster", pet_name="Harry")
describe_pet(pet_name="Rex", animal_type="dog")
Output:
I have a hamster named Harry.
I have a dog named Rex.
Variable Scope in Functions
Variables defined inside a function have a local scope, meaning they can only be accessed within that function.
def demonstrate_scope():
local_variable = "I am local"
print(local_variable)
demonstrate_scope()
# This will cause an error:
# print(local_variable) # NameError: name 'local_variable' is not defined
Global variables, on the other hand, are defined outside functions and can be accessed from anywhere.
global_variable = "I am global"
def show_global():
print(f"Inside function: {global_variable}")
show_global()
print(f"Outside function: {global_variable}")
Output:
Inside function: I am global
Outside function: I am global
Lambda Functions (Anonymous Functions)
Lambda functions are small, anonymous functions defined with the lambda
keyword. They're useful for short operations.
# Regular function
def double(x):
return x * 2
# Equivalent lambda function
double_lambda = lambda x: x * 2
print(double(5))
print(double_lambda(5))
Output:
10
10
Lambda functions are especially useful with functions like map()
, filter()
, and sorted()
:
numbers = [1, 5, 3, 9, 2, 6]
# Using lambda with map to double each number
doubled = list(map(lambda x: x * 2, numbers))
print(f"Doubled numbers: {doubled}")
# Using lambda with filter to get only even numbers
evens = list(filter(lambda x: x % 2 == 0, numbers))
print(f"Even numbers: {evens}")
# Using lambda with sorted to sort by remainder when divided by 3
sorted_by_remainder = sorted(numbers, key=lambda x: x % 3)
print(f"Sorted by remainder when divided by 3: {sorted_by_remainder}")
Output:
Doubled numbers: [2, 10, 6, 18, 4, 12]
Even numbers: [2, 6]
Sorted by remainder when divided by 3: [3, 6, 9, 1, 4, 2]
Functions in Data Analysis Context
Functions are essential in data analysis workflows. Let's see some examples that will be useful when working with Pandas:
Data Cleaning Function
def clean_name(name):
"""Clean a name by removing extra spaces and capitalizing."""
cleaned = name.strip().title()
return cleaned
# Example usage
names = ["john doe ", " jane smith", "BOB JOHNSON"]
cleaned_names = [clean_name(name) for name in names]
print(cleaned_names)
Output:
['John Doe', 'Jane Smith', 'Bob Johnson']
Data Transformation Function
def convert_temperature(celsius_temp):
"""Convert Celsius to Fahrenheit."""
fahrenheit = (celsius_temp * 9/5) + 32
return fahrenheit
# Creating a simple temperature dataset
celsius_temps = [0, 10, 20, 30, 40]
fahrenheit_temps = [convert_temperature(temp) for temp in celsius_temps]
for c, f in zip(celsius_temps, fahrenheit_temps):
print(f"{c}°C = {f}°F")
Output:
0°C = 32.0°F
10°C = 50.0°F
20°C = 68.0°F
30°C = 86.0°F
40°C = 104.0°F
Best Practices for Writing Functions
- Use descriptive names: Choose function names that clearly describe what the function does.
- Add docstrings: Document what your function does, its parameters, and return values.
- Single responsibility: Each function should do one thing and do it well.
- Limit parameters: Try to keep the number of parameters small.
- Return values: Be consistent with return values.
- Handle errors: Use try/except to handle potential errors.
Summary
Functions are a powerful feature in Python that allow you to:
- Organize code into reusable blocks
- Accept input through parameters
- Return output values
- Create modular and maintainable code
Mastering functions is essential for writing clean, efficient Python code and will be extremely valuable as you begin working with data analysis libraries like Pandas.
Practice Exercises
- Write a function that takes a list of numbers and returns the sum of all even numbers.
- Create a function that takes a string and returns True if it's a palindrome (reads the same forwards and backwards).
- Write a function that calculates the factorial of a number.
- Create a function that takes a list of strings and returns a new list with only the strings that start with a vowel.
- Write a temperature converter that can convert between Celsius, Fahrenheit, and Kelvin based on a unit parameter.
Additional Resources
If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)