Lesson goal: Data Science: Find the average of numbers in a data file

Previous: Find the total of some numbers | Home | Next: Find the maximum value

As in the last lessons, suppose sample.dat contains a list of amounts spent by patrons during lunch at a retaurant. Let's see if we can tell the owner what their average earnings were. In other words, let's find the sum of all numbers in the file sample.dat, them divide by how many numbers there are. Average = (Sum of all numbers)/(total number of numbers), right? ${\bar x}=\frac{1}{N} \Sigma x_i$.

As is typical in such work, we'll need to set up a loop so we can examine each number in the file. But we won't just print them to the screen. We'll apply some coding logic to try and figure what the sum of all numbers in the file is, and how many numbers went into the sum.

Now you try. Try to complete the code and find the minimum number in the file sample.dat.

Type your code here:


See your results here:

The code will not run, but here's our logic: We're using sum to keep track of the running total of the numbers, and N to count the number of numbers used. We'll compute the average for printing in the avg = line.

Look carefully at the code, what will you fill in for all of the ??s? Dismiss.

Show a friend, family member, or teacher what you've done!

Here is a share link to your code:

Does your code work? Want to run it on your iPhone?

Here's your code:

  1. Use [Control]-[C] (Windows) or [⌘]-[C] (MacOS) to copy your code.

  2. Paste it using [Control]-[V] (Windows) or [⌘]-[V] (MacOS) into this page

  3. Then click the "Use on iPhone" button that you'll see.