Python basics: variables, lists, loops and functions

Python is the programming language of machine learning. You store values in variables, keep many values in a list, repeat work with a loop, and package steps into a function you can reuse.

Why it matters

Every lesson after this one asks you to run code and change it. You don't need to be a programmer first, but you do need four ideas: variables, lists, loops and functions. With those you can read every example in this course. NumPy and PyTorch are then just faster tools built on the same four ideas.

The idea

Four ideas run through all the code in this course. A variable names a value. A list holds many values in order. A loop repeats work for each item. A function packages steps so you can use them again.

A kitchen. Variables are labelled jars. A list is a shelf of jars in a fixed order. A loop is "do this for every jar on the shelf". A function is a recipe card: hand it ingredients and it hands back a dish.

A jar keeps what you put in it. A variable can be given a new value at any time. Two names can also point at the same list: change the list through one name, and the other name sees the change too.

How it works

  1. Open a notebook: go to colab.research.google.com and choose New notebook. Type print(2 + 3) in the first cell and press Shift+Enter. Python runs it and shows 5. There is nothing to install.
  2. A variable is a name for a value: w = 3.0 stores the number 3.0 under the name w. Use the name later and Python fills in the value: w * 50 gives 150.0.
  3. A list keeps several values in order: sizes = [50, 80, 120]. Positions count from 0, so sizes[0] is 50 and sizes[2] is 120, and len(sizes) is 3.
  4. A for loop runs the indented lines once for each item. "for s in sizes:" followed by an indented "print(w * s)" prints 150.0, then 240.0, then 360.0. The 4 spaces of indentation are how Python knows which lines are inside the loop.
  5. An if runs its indented lines only when a test is true: "if s > 100:" lets through only the 120. A test such as s > 100 or s == 80 gives True or False.
  6. A function packages steps under a name. "def predict(size, w, b):" followed by an indented "return w * size + b" defines it; predict(80, 3.0, 0.0) calls it and gets back 240.0.
  7. Put them together: loop over the houses, call predict for each one, and add up the squared errors. That is the loss from the first lesson, written in plain Python.

Key points

Common mistakes

Not true: A function that prints its result also hands that result back to the code that called it.
In fact: Printing only shows a value on the screen. To hand it back, the function needs return; without it the caller gets None.

Not true: A list of 3 items: the last item is at position 3.
In fact: Counting starts at 0, so the three positions are 0, 1 and 2. Asking for position 3 is an error.

Part of Unit 0: Your toolkit in the free ML Foundations course.