None
In previous lessons, we used methods on lists and sometimes we saw a None output. None is a special data type that we see in Python. In other programming languages, you might see the word C‑style languages, Java, JS, SQL use Null, Python and Rust use None Null used for the same thing.
If you run print(type(None)), you will see NoneType. Excellent, problem solved! See you next lesson...
Just kidding.
Why Use None?
Let's say we have a variable a = None. Why would we ever want to do this?
Imagine you are developing a course. When a student first starts, before they have taken a test or turned in an assignment, their grade isn't $0$ (because they haven't failed yet) and it isn't $100$ (because they haven't earned it yet). Their grade is effectively "nothing."
In this situation, we use grade = None until we have an actual result to enter into the variable.
Try it out:
- Print grade.
- Print grade type.
By using None, you tell the program that the variable exists, but it doesn't have a value yet.
Time to experiment!
Coding Exercises (VS Code) Instructions:
- Create a file named none.py in your part27 folder.
- Complete the tasks and use # comments to explain your answers.
Exercise 1: The New Enrollment
A new student has just joined the school database. They exist in the system, but since they haven't attended any classes yet, they don't have a GPA.
-
Task: Create a variable named
student_gpaand assign it the value ofNone. -
Goal: Print the variable and its
type()to confirm it is aNoneType.
Exercise 2: The Return Value Mystery
Some list methods don't return a new list; they just change the original and return "nothing." Let's see this in action.
-
Starting List:
colors = ['red', 'blue', 'green'] -
Task: Create a variable called
resultand set it equal tocolors.append('yellow'). -
Goal: Print
result. Observe that even though the color was added to the list, the action itself returnedNone.
Exercise 3: The Placeholder Logic
In programming, we often check if a variable is still "empty" before we perform a calculation.
-
Task: Create a variable
final_scoreand set it toNone. -
Task: On the next line, re-assign
final_scoreto a number of your choice. -
Goal: Print
final_scoreto show how it transitioned from "nothing" to a value.
Don't Forget to commit and Push!