Foundations · Lesson 2/9

Python for AI — Your First Tools

40 min 2 exercises 1 quiz Graded labs: 1

What you'll learn

  • Why Python owns the AI world
  • Lists and loops for handling data
  • The idea behind NumPy (arrays of numbers)
  • You'll compute real statistics on data, live

The language of intelligence 🧠

Almost all AI is built in Python — not because it's fastest, but because it's the easiest to think in, and every AI tool (NumPy, pandas, PyTorch, TensorFlow) lives there. AI is, at its core, doing math on big piles of numbers, and Python makes that readable.

Everything starts with data in lists:

temperatures = [22, 25, 19, 30, 28]

# the essentials for AI data work:
print(len(temperatures))       # 5  — how many
print(sum(temperatures))       # 124 — total
print(max(temperatures))       # 30 — biggest
print(min(temperatures))       # 19 — smallest
average = sum(temperatures) / len(temperatures)
print(average)                 # 24.8

To transform every number at once, Python has a beautiful tool called a list comprehension:

doubled = [t * 2 for t in temperatures]   # [44, 50, 38, 60, 56]
hot_days = [t for t in temperatures if t > 24]  # [25, 30, 28]

Read it as "give me t * 2 for each t in temperatures." This one idea replaces whole loops and is everywhere in AI code.

Real AI uses NumPy, a library that makes arrays of numbers blazing fast and lets you do math on a whole array at once (array * 2 doubles every element). But the mental model is exactly the list thinking above — NumPy just makes it fast enough for millions of numbers.

Dictionaries: giving data a name, not just a slot 🏷️

Lists are great when order is all that matters. But real-world AI data is usually a record — a set of named fields, like one row of a spreadsheet: {"name": "Ahmed", "age": 29, "score": 0.91}. Python's tool for this is the dictionary (dict): a collection of key → value pairs.

student = {"name": "Sara", "score": 88}
print(student["name"])   # "Sara"  — look up by key, not position
student["score"] = 91    # update a value
student["passed"] = True # add a new field

Dictionaries are everywhere in AI code: a dataset row, a model's configuration ({"learning_rate": 0.01, "epochs": 10}), or the JSON a model API sends back. pandas (the library you'll meet constantly after this lesson) is essentially a giant, fast table built out of exactly this idea — every column is a named key, every row a record.

One pattern you'll use constantly is grouping: counting or summing values by a category. For example, given a list of purchases, "total spent per customer." The trick is a dictionary that starts empty and grows one key at a time:

totals = {}
for name, amount in [("Sara", 20), ("Ali", 15), ("Sara", 5)]:
    totals[name] = totals.get(name, 0) + amount
# totals == {"Sara": 25, "Ali": 15}

.get(key, 0) is the safe way to read a key that might not exist yet — it returns 0 instead of crashing. This exact pattern (loop + dictionary + .get) is the seed of every "group by" you'll ever write, whether by hand or with pandas' .groupby().

Exercise 1

Data preparation is step one of every AI project. Write normalize(data) that scales a list of numbers to the 0–1 range using min-max normalization:

normalized = (x - min) / (max - min) for each value.

Example: [10, 20, 30] → [0.0, 0.5, 1.0]

Exercise 2

Practice the "group by" pattern used everywhere in real data work. Write total_per_customer(purchases) where purchases is a list of (name, amount) tuples. Return a dictionary mapping each customer name to their total spend.

Example: [("Sara", 20), ("Ali", 15), ("Sara", 5)] → {"Sara": 25, "Ali": 15}

Real-world case study: NumPy, the library under everything 🔍

In 2020, the journal Nature published a paper titled "Array programming with NumPy" — an unusual honor for a piece of open-source software. It documented something remarkable: NumPy, a free library maintained largely by volunteers, had quietly become the numerical foundation underneath nearly the entire scientific Python stack — pandas, scikit-learn, PyTorch, and TensorFlow all convert your data into NumPy-style arrays before doing serious math on it.

The reason traces straight back to the list-vs-array idea from this lesson: plain Python lists are flexible but slow for millions of numbers, because Python checks each element's type one by one. NumPy stores numbers in one tightly-packed block of memory and processes them using fast, compiled C code — so array * 2 multiplies a million numbers nearly as fast as multiplying one.

That single design decision — trade some flexibility for raw speed on numeric arrays — is why a research team can train a model on millions of images in hours instead of years. Every framework you'll use in this AI track (pandas' tables, PyTorch's tensors) is, underneath, still that same idea: numbers packed tightly, so math on huge piles of them stays fast.

Lab exercise 1

PythonGraded in Code Lab

Normalise a feature. Models train better when numeric features share a scale. Min-max scaling maps the smallest value to 0 and the largest to 1:

scaled = (x - min) / (max - min)

Read one line of space-separated numbers from standard input and print the scaled values on one line, separated by single spaces, each with exactly 3 decimals (0.250).

If every number is identical (max == min) there is nothing to scale: print 0.000 for each value. Do not use external libraries.

Visible tests (4)
  • Scales a small list
  • Handles negatives and decimals
  • All values equal prints zeros
  • A single value
Example run
Input
10 20 30 40 50
Expected output
0.000 0.250 0.500 0.750 1.000
Starter code
values = [float(token) for token in input().split()]

# TODO 1: find the smallest and largest value
# TODO 2: handle the "all values equal" case (avoid dividing by zero)
# TODO 3: scale each value and print them on one line with 3 decimals, e.g. f"{x:.3f}"
print(" ".join(f"{v:.3f}" for v in values))
Try in Code Lab

Hints and instant feedback are in Code Lab. Optional practice: it does not block finishing the lesson.

JavaScript and Python also run in your browser without an account; other languages use the secure server runner and need a free account.

Quick quiz

Question 1 of 6

Why is Python dominant in AI?

Question 2 of 6

What does [t*2 for t in nums] do?

Question 3 of 6

Why normalize data to 0–1?

Question 4 of 6

What is a Python dictionary best used for?

Question 5 of 6

In the group-by pattern `totals[name] = totals.get(name, 0) + amount`, what does `.get(name, 0)` do?

Question 6 of 6

Why does NumPy make array math so much faster than plain Python lists?

Summary

  • Python is the language of AI thanks to readability + libraries
  • Lists, len/sum/max/min, and list comprehensions handle data
  • Dictionaries store named key → value records and power the "group by" pattern
  • NumPy makes array math fast at scale by packing numbers tightly and using compiled C
  • You wrote a real min-max normalizer and a group-by total-per-customer function
  • Case study: NumPy's 2020 Nature paper shows how one array library underpins pandas, scikit-learn, PyTorch, and TensorFlow

Next: Math for ML — the surprisingly small amount of math you actually need, explained simply.

Practice

Reading is not learning until you run something. Pick one.

Graded lab exercises