Main Content

Finding sum, minimum, maximum and average in Python (and Ruby)

Archive - Originally posted on "The Horse's Mouth" - 2015-01-19 18:04:24 - Graham Ellis

A fresh example (in Python) from today's "learning to program in" course ... finding the number, sum, minimum and maximum of a series of numbers typed in. See [here].

We start off with zero for the count and sum to date, but we do not initialise the minimum or the maximum as we don't know what they would be initialised to - instead, when we read the first value we store that into the minimum (so far) and maximum (so far) variables.

Note the contrast to the similar Ruby example ([here] in which we initialise the variables to nil - a slightly different strategy caused by different scoping rules.

In all cases, we also need to check for a "divide by zero" if there is no input data. My Python program from today does that, I note; the previous Ruby one doesn't have that in.