So far in #100DaysOfPython we've looked at a bunch of fundamental and essential Python concepts, like lists, tuples, dictionaries, and iteration over them. We've also looked at list comprehension.

Today I have a short but fun challenge that will require the knowledge you’ve already acquired!

This post is part of #100DaysOfPython, check out yesterday's post here if you haven't already. Or go to the index of all 100 days.

A student is defined in the following fashion:

  "name": "Jose",
  "marks": [56, 77, 95]

Given a list of students, calculate the average grade of the entire class.

You’ll have to keep a running total of the sum of all marks in the entire class, and how many marks in total there are. Then, divide one by the other to get an average.

Remember each student may have a different number of marks (e.g. some may have 1, some may have 5).

Two functions that may come in handy

We’ve not looked at functions yet (that’s tomorrow’s topic!), but nonetheless I’m going to give you two that you will find useful in this challenge.

  • The len function; and
  • The sum function.

The len function

Given an iterable, such as a list or a tuple, the len function will give you the number of elements in it. That is:

  • For [1, 3, 5], len([1, 3, 5]) will give you 3.
  • For (13, 45, 66, 90), len((13, 45, 66, 90)) will give you 4.

The sum function

Given an iterable, such as a list or a tuple, the sum function will give you the total of all elements added together. For example:

  • For [1, 3, 5], sum([1, 3, 5]) will give you 8.
  • For (13, 45, 66, 90), sum((13, 45, 66, 90)) will give you 214.

Challenge code

Here’s some starter code you can use to begin the assignment. You can copy it from below:

students = [
  { "name": "Jose", "marks": [56, 77, 97] },
  { "name": "Rolf", "marks": [45, 80] },
  { "name": "Anna", "marks": [87, 75, 100, 95, 98] },
  { "name": "Mary", "marks": [67, 70, 80] },
  { "name": "Stuart", "marks": [44, 55] },
  { "name": "Sophie", "marks": [86, 90, 100, 100] },

for student in students:

The starter code above has a list of students that you can use. It also defines an iteration over the students list. You can use the iteration, or you can use list comprehension if you prefer.

Every block in Python needs to have at least some code in it. The for loop is no exception. Here we don’t have anything to put inside the loop, so instead we can put pass. It just means “do nothing”, but gives Python something to put in there!

Let us know how you get on with the challenge on Twitter @TecladoCode. You can also use the hashtag #100DaysOfPython 💪!

Good luck, and I'll see you tomorrow!