Python Basics: How to Pass Lists into Functions (With Code)
# This program demonstrates how to create a function that takes a list as a parameter and calculates the sum of its numbers.
# Define a function named 'calculate_sum' that accepts one parameter called 'numbers_list'
def calculate_sum(numbers_list):
# Initialize a variable 'total' to 0 to keep track of the running sum
total = 0
# Start a loop to iterate through each individual item in the 'numbers_list'
for number in numbers_list:
# Add the current number to the 'total' variable
total += number
# Return the final calculated sum back to where the function was called
return total
# Create a list of numbers to test the function
my_numbers = [10, 20, 30, 40, 50]
# Call the 'calculate_sum' function, pass 'my_numbers' as an argument, and store the result in 'result'
result = calculate_sum(my_numbers)
# Print the final result to the console with a descriptive message
print("The sum of the list elements is:", result)
# Define a function named 'calculate_sum' that accepts one parameter called 'numbers_list'
def calculate_sum(numbers_list):
# Initialize a variable 'total' to 0 to keep track of the running sum
total = 0
# Start a loop to iterate through each individual item in the 'numbers_list'
for number in numbers_list:
# Add the current number to the 'total' variable
total += number
# Return the final calculated sum back to where the function was called
return total
# Create a list of numbers to test the function
my_numbers = [10, 20, 30, 40, 50]
# Call the 'calculate_sum' function, pass 'my_numbers' as an argument, and store the result in 'result'
result = calculate_sum(my_numbers)
# Print the final result to the console with a descriptive message
print("The sum of the list elements is:", result)
Comments
Post a Comment