Stats
Loops can be used to calculate statistics of a list (or an iterator) of numbers. Let's see how we can calculate the sum, minimum, and maximum of a list of numbers.
Sum
To calculate sum of a list of numbers, we can use a for
loop to iterate over the list and add each number to a variable that keeps track of the sum. Here's an example:
sum_of_numbers = 0
for num in range(1, 101):
sum_of_numbers += num
print(f"Sum: {sum_of_numbers}")
print(f"Average: {sum_of_numbers / 100}")
Not that at the last line we also calculate the average of the numbers by dividing the sum by the length of the list.
Output of the program:
Sum: 5050
Average: 50.5
Minimum and Maximum
Here's how we can calculate the minimum and maximum of a list of numbers:
numbers = [10, 6, 2, 3, 9, 0, 5, 7, 1, 4, 8]
min = numbers[0]
max = numbers[0]
for number in numbers:
if number < min:
min = number
if number > max:
max = number
print(f"Min: {min}")
print(f"Max: {max}")
We first initialize the minimum and maximum to the first element of the list. Then we iterate over the list and update the minimum and maximum if we find a smaller or larger number. Finally, we print the minimum and maximum:
Min: 0
Max: 10
Notice how we use the if
statement inside the for
loop.
Built-in Functions
In practice, we don't need to write our own functions to calculate the sum, minimum, and maximum of a list of numbers. Python provides built-in functions for these purposes. Here's how we could use them:
numbers = [1, 2, 3, 4, 5]
print("Sum:", sum(numbers))
print("Min:", min(numbers))
print("Max:", max(numbers))
and here's the output:
Sum: 15
Min: 1
Max: 5
In general, in programming it's a good idea to use built-in functions whenever possible. They are usually faster and more reliable than our own functions.