Totaling the Values in a List in Python:-
Assuming a list contains numeric values, to calculate the total of those values you use a loop with an accumulator variable. The loop steps through the list, adding the value of each element to the accumulator. Program (specified below) demonstrates the algorithm with a list named numbers.
(total-list.py)
# This program calculates the total of the values in a list #.
def main ( ):
# Create a list.
numbers = [2, 4, 6, 8, 10]
# Create a variable to use as an accumulator.
total = 0
# Calculate the total of the list elements.
for value in numbers:
total += value
# Display the total of the list elements.
print 'The total of the elements is', total
# Call the main function.
main ( )
Output
The total of the elements is 30


LinkBack URL
About LinkBacks
Reply With Quote

LinkBacks Enabled by vBSEO
Bookmarks