Session 8: Something about Nothing

Session 8: Something about Nothing#

Introduction#

You have learned that pretty much everything in Python is an object - and it turns out that even includes the concept of “nothing”…

Task 1#

  1. In a terminal window, navigate to your PHAR2062/Session 8 - Something about Nothing folder.

  2. Start a fresh Jupyter notebook.

  3. In the first cell, write:

    test_scores = [45, 54, 67, 72, 44]
    n_scores = len(test_scores)
    print(n_scores)
    
  4. Then run the cell.

Analysis#

Nothing unexpected here, I’m sure; but look at lines 2 and 3. Both these lines feature functions (len() and print()), but they are a bit different, in that len() returns somthing - a value that here is assigned to the variable n_scores - while print() doesn’t return anything.

Or does it??

Task 2#

  1. Edit line 3 of the code and add a further line, so it becomes:

    test_scores = [45, 54, 67, 72, 44]
    n_scores = len(test_scores)
    result = print(n_scores)
    print(result)
    print(type(result))
    
  2. Then run it.

Analysis#

When we said that print() doesn’t return “anything” that was true - because it returns “nothing”, or more exactly, a value of None. In the code here we have assigned this value of None to a variable, result, which in the last line we see has a type of NoneType.

The ability to recognise and deal with “nothing” can be very useful. For example, it helps when you have a collection of data that includes missing values. Let’s look at an example.

Task 3#

  1. Copy the code below into a fresh notebook cell, and run it:

    test_scores = [45, 54, None, 72, 44]
    # Calculate the mean score obtained (for those who took the test):
    score_sum = 0
    valid_scores = 0
    for score in test_scores:
        if score is not None:
            score_sum = score_sum + score
            valid_scores = valid_scores + 1
    print('The mean score was ', score_sum / valid_scores)
    

Analysis#

This code snippet demonstrates a simple, but very typical, situation in which None is useful. Note that in Python None (written without quotes round it) is the None literal, in the same way that "hello" is a string literal or 12.0 a float literal.

Note

Data sources that need to flag up missing or invalid values may do this in many different ways. Some may use a particular value - maybe “999.999” or “-1” to signal this, but that is dangerous unless the data reader knows the “rules”. Within Python, None provides an unambiguous alternative.

Summary#

Here you have been introduced to a further Python data type: the NoneType. Variables of NoneType can only take one value - None.