Practical Function Examples
Overview
Put everything you've learned about functions into practice! You'll build complete, real-world programs that combine multiple function concepts - from simple calculators to data processing tools. This lesson reinforces all the function concepts you've learned and shows how they work together in practical applications.
What You Will Learn in This Lesson
By the end of this lesson, you will know:
- Combining concepts: See how all function concepts work together.
- Real-world applications: Build practical programs using functions.
- Code organization: Learn how to structure programs with multiple functions.
- Best practices: Apply everything you've learned in real scenarios.
Why This Matters
This lesson brings together everything you've learned about functions. You'll see how parameters, return values, default arguments, helper functions, and more work together to solve real problems. By building complete programs, you'll gain confidence in using functions and understand how professional Python code is organized.
Example 1: Temperature Converter
Let's build a temperature converter that converts between Celsius and Fahrenheit:
def celsius_to_fahrenheit(celsius):
"""Convert Celsius to Fahrenheit."""
return celsius * 9/5 + 32
def fahrenheit_to_celsius(fahrenheit):
"""Convert Fahrenheit to Celsius."""
return (fahrenheit - 32) * 5/9
def convert_temperature(value, unit="C"):
"""
Convert temperature between Celsius and Fahrenheit.
Parameters:
value (float): The temperature value
unit (str): "C" for Celsius or "F" for Fahrenheit (default: "C")
Returns:
tuple: (converted_value, target_unit)
"""
if unit == "C":
converted = celsius_to_fahrenheit(value)
return (converted, "F")
else:
converted = fahrenheit_to_celsius(value)
return (converted, "C")
# Use the functions
result = convert_temperature(25, "C")
print(f"25°C = {result[0]}°{result[1]}")
Helper Functions
The program uses two helper functions (celsius_to_fahrenheit and fahrenheit_to_celsius) that each handle one specific conversion. This breaks down the problem into smaller, manageable pieces.
Main Function
The convert_temperature function uses a default parameter (unit="C") and calls the appropriate helper function based on the input. It returns a tuple with the converted value and the target unit.
Documentation
Each function has a docstring explaining what it does, what parameters it takes, and what it returns. This makes the code easy to understand and use.
Key Concept: This example shows how to organize code with multiple functions. Each function has a single responsibility - one converts C to F, another converts F to C, and the main function coordinates between them. This separation makes the code easier to understand, test, and maintain.
Practice: Temperature Converter
Try It YourselfTry running the temperature converter and experiment with different values:
What happened? The program uses two separate functions, each handling one direction of conversion. This makes the code clear and easy to understand. Each function has a single job - convert from one unit to another. You can use these functions independently or combine them in a larger program. This is how professional code is organized - small, focused functions that work together!
Example 2: Grade Calculator
Let's build a grade calculator that processes student scores:
def calculate_average(scores):
"""Calculate the average of a list of scores."""
if len(scores) == 0:
return 0
return sum(scores) / len(scores)
def get_letter_grade(average):
"""Convert numeric average to letter grade."""
if average >= 90:
return "A"
elif average >= 80:
return "B"
elif average >= 70:
return "C"
elif average >= 60:
return "D"
else:
return "F"
def process_student(name, scores):
"""
Process a student's scores and return their grade information.
Parameters:
name (str): Student's name
scores (list): List of numeric scores
Returns:
dict: Dictionary with name, average, and letter grade
"""
average = calculate_average(scores)
letter = get_letter_grade(average)
return {
"name": name,
"average": average,
"grade": letter
}
# Use the functions
student = process_student("Alice", [85, 90, 88, 92])
print(f"{student['name']}: {student['average']:.1f}% ({student['grade']})")
How It Works
This program uses multiple functions working together. calculate_average handles the math, get_letter_grade handles the conversion logic, and process_student coordinates everything. Each function has a clear purpose, making the code easy to understand and modify. If you need to change how averages are calculated, you only change one function!
Practice: Grade Calculator
Try It YourselfTry using the grade calculator with different scores:
What happened? The program uses two functions that work together. First, calculate_average processes the list of scores and returns the average. Then, get_letter_grade takes that average and converts it to a letter grade. By separating these concerns into different functions, the code is easier to understand and test. You could test each function independently, or modify one without affecting the other!
Example 3: Data Processing Pipeline
Let's build a program that processes a list of numbers:
def filter_positive(numbers):
"""Return only positive numbers from a list."""
return [n for n in numbers if n > 0]
def square_numbers(numbers):
"""Square each number in a list."""
return [n * n for n in numbers]
def process_data(numbers, filter_negatives=True):
"""
Process a list of numbers through a pipeline.
Parameters:
numbers (list): List of numbers to process
filter_negatives (bool): Whether to filter out negative numbers (default: True)
Returns:
list: Processed list of numbers
"""
if filter_negatives:
numbers = filter_positive(numbers)
return square_numbers(numbers)
# Use the functions
data = [-2, -1, 0, 1, 2, 3]
result = process_data(data)
print(result) # Output: [1, 4, 9]
Key Concept: This example shows how functions can work together in a pipeline. Data flows from one function to another, with each function transforming it in some way. The main function coordinates the process, using default parameters to make common cases easier. This pattern is very common in real-world programming!
Putting It All Together
These examples show how all the function concepts work together:
Multiple Functions
Programs use multiple functions, each with a specific purpose.
def helper1(): ...
def helper2(): ...
def main(): ...
Function Composition
Functions call other functions, building complex behavior from simple pieces.
def main():
result = helper1()
return helper2(result)
Best Practices
Good programs use functions to organize code. Each function should do one thing well. Functions should be documented with docstrings. Use default parameters for common cases. Return values instead of printing when possible. These practices make your code professional, maintainable, and easy to understand.
End-of-Lesson Exercises
Exercise 1: Build a Calculator Function
Create a function named calculate that takes three parameters: num1, operation (one of "+", "-", "*", "/"), and num2. It should return the result of the operation. Include a docstring explaining what it does. Test it with different operations.
Use if/elif statements to check the operation and perform the correct calculation.
Exercise 2: Create a Text Processor
Create a function named process_text that takes a string and two optional parameters: uppercase (default False) and reverse (default False). It should return the processed text. Create helper functions to_uppercase and reverse_text to handle the transformations. Include docstrings.
Use nested helper functions or separate functions, and apply transformations based on the parameters.