Coding Exercise #12
🌶️🌶️
The following code calculates the sum, maximum, and minimum of the numbers list.
# List of numbers
numbers = [10, 20, 30, 40, 50]
# Calculate the sum
total_sum = 0
for number in numbers:
total_sum += number
# Calculate the average
average = total_sum / len(numbers)
# Find the maximum
max_number = numbers[0]
for number in numbers:
if number > max_number:
max_number = number
# Find the minimum
min_number = numbers[0]
for number in numbers:
if number < min_number:
min_number = number
# Print the results
print(f"Sum: {total_sum}")
print(f"Average: {average}")
print(f"Maximum: {max_number}")
print(f"Minimum: {min_number}")👉 The code is written using procedural programming. Your task is to refactor/rewrite that program by using functions. The functions should take the numbers list as input and return the sum, average, maximum, and minimum each.
💡 Please note that refactoring consists of changing the code without changing the functionality of the code. The purpose of refactoring is to make the code easier to understand and easier to maintain and extend.
Press the button below to go to the code editor:
Use the button below to see the solution:
Subscribe below to get a new Python project or exercise daily or upgrade to our paid plan to view the archive of projects, exercises, and solutions.



I have done mine. Below is my code:
# List of numbers
numbers = [10, 20, 30, 40, 50]
# Calculate the sum
def calculate_sum(numbers):
total_sum = 0
for number in numbers:
total_sum += number
return total_sum
# Calculate the average
def calculate_average(numbers):
total_sum = calculate_sum(numbers)
average = total_sum / len(numbers)
return average
# Find the maximum
def find_max(numbers):
max_number = numbers[0]
for number in numbers:
if number > max_number:
max_number = number
return max_number
# Find the minimum
def find_min(numbers):
min_number = numbers[0]
for number in numbers:
if number < min_number:
min_number = number
return min_number
# Call the functions
total_sum = calculate_sum(numbers)
average = calculate_average(numbers)
max_number = find_max(numbers)
min_number = find_min(numbers)
# Print the results
print("Sum:", total_sum)
print("Average:", average)
print("Maximum:", max_number)
print("Minimum:", min_number)