DVP IBM AI Engineering
Reference

Primer 1 — Reading Python

Variables, lists, loops, functions, imports — enough to read model.fit(X, y)

Do this before Course 1. Goal: not writing Python yet — reading it without fear. Every snippet here runs in the Code Lab. Paste, run, change something, run again.


Variables — names stuck on values

fps = 29.97
codec = "XDCAM HD422"
frames = 1798

A variable is a label. No types declared, no ceremony — the value decides the type. fps holds a decimal number (a float), codec holds text (a string), frames a whole number (an int).

duration = frames / fps
print(duration)          # 59.99...
print(round(duration))   # 60

print() shows a value. round() rounds one. Words followed by parentheses are functions — machines that take something in and hand something back.

Self-check — answer without looking
  1. What type is 29.97? What type is "29.97"?
  2. Predict before running: what does print(round(1798 / 29.97)) print?

Lists — ordered stacks of values

The single most common structure in this certificate.

takes = [12.5, 8.0, 22.1, 15.3]

print(takes[0])      # 12.5   ← counting starts at ZERO
print(takes[3])      # 15.3
print(takes[-1])     # 15.3   ← minus one = last item
print(len(takes))    # 4      ← len() = how many

Indexing starts at 0. Every off-by-one confusion you will ever have comes from this. The first item is [0], the fourth is [3], the last is [-1].

takes.append(9.9)    # add to the end
print(takes)         # [12.5, 8.0, 22.1, 15.3, 9.9]

takes.append(...) — the dot means "do something that belongs to this thing". That's a method: a function attached to a value. Lists know how to append; strings don't.

Self-check — answer without looking
  1. clips = ["a.mov", "b.mov", "c.mov"] — what is clips[1]? (not "a.mov"!)
  2. What does len(clips) return?

Loops — do it for every item

takes = [12.5, 8.0, 22.1, 15.3]

for t in takes:
    print("take length:", t)

Read it as English: for each t in takes, do the indented stuff.

Two things matter enormously:

total = 0
for t in takes:
    total = total + t
print("total:", total)       # 57.9
print("mean:", total / len(takes))

That's the pattern behind every "average the loss over the batch" you'll meet later.

Self-check — answer without looking
  1. Why is print("total:", total) NOT indented?
  2. Rewrite the loop so it counts only takes longer than 10. (Hint below.)
count = 0
for t in takes:
    if t > 10:
        count = count + 1

if works like for: condition, colon, indented body. Double indent = inside the loop and inside the if.


Functions — name a recipe, reuse it

def mean(values):
    total = 0
    for v in values:
        total = total + v
    return total / len(values)

print(mean([12.5, 8.0, 22.1, 15.3]))   # 14.475
print(mean([1, 2, 3]))                  # 2.0

The thing to internalise: mean([1,2,3]) is 2.0 — a call is an expression that becomes its result. So print(mean(x)) means "compute mean of x, then print that".

Self-check — answer without looking
  1. What's the difference between the parameter values and the argument [1, 2, 3]?
  2. What does a function return if it has no return line?

Imports — using other people's functions

import math
print(math.sqrt(64))          # 8.0

from math import sqrt
print(sqrt(64))               # 8.0 — same thing, shorter name

A module is a file of functions someone else wrote. import math brings the whole toolbox in; you reach inside it with the dot. from math import sqrt pulls one tool out and puts it on your bench.

This is 90% of what the course's opening lines are:

from sklearn.linear_model import LogisticRegression
import numpy as np

Line 1: from the sklearn toolbox, sub-drawer linear_model, take LogisticRegression. Line 2: import numpy and call it np from now on (as renames). Pure convention — every ML script alive uses np.


Now read real course code

This is the first pattern Course 1 shows you. You can now decode every line:

from sklearn.linear_model import LogisticRegression   # get the tool

model = LogisticRegression()      # make one — the () CALLS it, like a function
model.fit(X_train, y_train)       # a method: "model, do your fit thing with this data"
predictions = model.predict(X_test)   # another method; hand back a list-like of answers

You don't need to know how fit works yet — Course 1 teaches that. You need to stop seeing these four lines as hieroglyphics. They're: import tool → make one → train it → use it.

Self-check — the one that matters

Without running it, say in plain English what each line does:

from sklearn.cluster import KMeans
km = KMeans(n_clusters=3)
km.fit(data)
labels = km.predict(data)

(That n_clusters=3 is a keyword argument — naming the argument as you pass it. Python code does this constantly for readability.)


Primer 1 in one page