Command Palette

Search for a command to run...

Hectal
PHASE 0Beginner ~28 min· topic 2 of 8

Topic 0.2

What Python Is and Why the AI World Runs on It

In one line

Python is a free, general-purpose programming language designed to be easy to read. It is the main language of AI and data work because it is quick to write and because its heavy number-crunching is done by fast libraries written in C, which Python code drives.

Think of it like this

A film director. The director does not carry the cameras or build the sets; specialists do that heavy work. The director gives short, clear instructions and the specialists carry them out fast. Python is the director's language. In AI work, short Python instructions drive highly optimised libraries that do the heavy maths.

Words you'll meet

New words in this topic, in plain English. Come back here whenever one feels fuzzy.

High-level language
A language close to human thinking that hides the machine's details. Python is high-level.
General-purpose
Useful for many kinds of programs, not just one field.
Open source
The source code is public, and anyone may use, study and improve it for free.
Syntax
The grammar rules of a programming language: what counts as correctly written code.
Indentation
Spaces at the start of a line. In Python, indentation shows which lines belong together.
Library
Code that someone else wrote and packaged so you can use it in your programs.
Standard library
The large set of libraries that comes installed with Python itself.
Package
A library prepared so it can be installed and shared, usually through PyPI.
PyPI
The Python Package Index, the public online store of free Python packages, at pypi.org.
NumPy
The most-used Python library for fast maths on large blocks of numbers. Phase 14 teaches it.
Compiled code
Code already translated into the instructions a processor runs directly, so it runs fast. C and C++ programs are compiled.
Memory
The computer's short-term workspace, where a running program keeps its values.
List
A row of values in square brackets, such as [72, 45, 90]. Phase 4 teaches lists.
Loop
Code that repeats some steps. Phase 2 teaches loops.

Step by step

01Readable on purpose

Read this program aloud. Even without knowing Python, you can probably tell what it does: it looks at each mark, and if the mark is 50 or more it says "pass", otherwise "try again".

marks = [72, 45, 90] remembers a list: a row of values in square brackets (Phase 4). for repeats the indented lines once for each mark (Phase 2). if and else choose between two paths (Phase 2). >= means "greater than or equal to". You will learn each of these properly later; for now just read.

Notice what is not there: no semicolons, no curly braces, no declarations of what kind of value marks is. The colon and the indented lines carry the structure. Topic 0.6 explains these rules.

main.pywhole filepython
marks = [72, 45, 90]

for mark in marks:
    if mark >= 50:
        print(mark, "pass")
    else:
        print(mark, "try again")

02The same idea in another language

For comparison, here is one line of output, "Hello", in Java, a language used widely for large business systems. Java asks you to say much more before anything happens. Neither is wrong: Java's extra rules catch some mistakes early and help very large teams. Python optimises for getting an idea into working code fast.

If you already know Java, Hectal's Core Java course at /java covers that side. Nothing in this course depends on it.

Main.javawhole filejava
public class Main {
    public static void main(String[] args) {
        System.out.println("Hello");
    }
}

03Batteries included

Python's standard library means many jobs need no extra installation. The import word loads a ready-made tool. Here statistics gives the average of some numbers and math gives a square root.

You will meet import properly in Phase 6. For now, notice the pattern: say which tool you want, then use it by name.

main.pywhole filepython
import math
import statistics

print(math.sqrt(144))
print(statistics.mean([72, 45, 90]))
terminal
$ python main.py
── expected output ──
12.0
69

04Where Python is used

AI and machine learning: training models (PyTorch), calling language models, building assistants and agents. Data: cleaning, analysing and charting data (pandas, NumPy). Web back ends: the server side of websites and APIs (FastAPI, Django). Automation: scripts that rename files, fill spreadsheets, test systems or glue tools together. Science and finance: simulations, statistics, research code.

This course teaches the language itself first (Phases 0 to 13), then the data toolkit (Phase 14), APIs and services (Phase 15) and the AI-era toolkit (Phase 16).

Where Python is useddiagram
Rendering diagram…

05Why slow Python can still be fast

A loop repeats some steps. Adding many numbers in a plain Python loop takes many small steps, and each step has some extra work attached. NumPy stores the numbers in one tight block of memory and adds them in compiled C code, in one call. The Python line is short; the work underneath is fast.

The example below does the same sum both ways and gets the same answer. range(1, 10_001) makes the numbers 1 to 10,000, list(...) keeps them in a list, and for n in numbers repeats the indented line once per number (Phase 2). import numpy as np loads NumPy under the short name np. On real data the NumPy way is typically tens of times faster, and Phase 14 explains exactly why. This split, Python on top and compiled code underneath, is the design of the whole AI software stack.

main.pywhole filepython
import numpy as np

numbers = list(range(1, 10_001))        # the numbers 1 to 10,000

total = 0
for n in numbers:                       # ten thousand small Python steps
    total = total + n
print("Loop: ", total)

array = np.array(numbers)               # one block of memory
print("NumPy:", array.sum())            # one call into fast C code
Why slow Python can still be fastdiagram
Rendering diagram…

06Who decides what Python is

Changes to the language are proposed in public documents called PEPs (Python Enhancement Proposals). Each has a number. PEP 8 is the style guide most Python code follows, and PEP 20, "The Zen of Python", is a short list of the language's guiding ideas. You can read it by running import this.

A small elected Steering Council of core developers makes the final decision on PEPs. You will see PEP numbers mentioned whenever this course introduces a newer feature.

Try it yourself

  1. 1

    Edit the marks

    In the first example, change the list to [72, 45, 90, 50, 49] and predict the five lines of output before running. Pay attention to 50 and 49: >= means "greater than or equal to".

  2. 2

    Use another battery

    In the second example, add the line print("Lowest mark:", min(marks)) at the end and run it. Then change math.sqrt(144) to math.sqrt(2) and look at how many digits Python shows.

  3. 3

    Read the Zen

    Run the last example. Pick the line you understand least and keep it in mind: by the end of the course it should make sense. "Errors should never pass silently" is the idea behind Topic 0.7 and all of Phase 7.

Code & diagrams

Python reads almost like English New tab

Change a mark, or add another number to the list, and run it again.

Sign in to run this example in your browser.

Expected output

72 pass
45 try again
90 pass
Batteries included: the standard library New tab

Nothing extra was installed for this. math and statistics come with Python.

Sign in to run this example in your browser.

Expected output

Square root of 144: 12.0
Average mark: 69
Highest mark: 90
How many marks: 3
Python on top, fast code underneath New tab

The first run downloads NumPy into your browser, so it takes a few seconds. Both ways give the same total.

Sign in to run this example in your browser.

Expected output

Loop:  50005000
NumPy: 50005000
The Zen of Python New tab

A hidden message inside Python: its design ideas in 19 lines. Read the first seven carefully.

Sign in to run this example in your browser.

Expected output

The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!

Break it on purpose

Errors are the best teachers. Make each change, read the error, guess what went wrong, then reveal the answer.

Break #1

Remove the indentation

In the first example, delete the spaces before print(mark, "pass") so it starts at the same position as the if above it. Run it.

main.pywhole filepython
marks = [72, 45, 90]

for mark in marks:
    if mark >= 50:
    print(mark, "pass")
    else:
        print(mark, "try again")
terminal
$ python main.py
── what you'll see ──
File "main.py", line 5
print(mark, "pass")
^^^^^
IndentationError: expected an indented block after 'if' statement on line 4

Break #2

Import something that doesn't exist

In the second example, change import statistics to import statistic (no final s) and run it.

terminal
$ python main.py
── what you'll see ──
Traceback (most recent call last):
File "main.py", line 2, in <module>
import statistic
ModuleNotFoundError: No module named 'statistic'

Myth vs fact

Myth

Python is only a beginner's language.

Fact

Python is gentle to start with, and it also runs production systems at very large companies and nearly all AI research. Easy to read does not mean limited.

Myth

Python is too slow for serious work.

Fact

Pure Python loops are slow, but serious Python work hands the heavy computation to compiled libraries (NumPy, PyTorch) or to databases and other services. The slow part is rarely where the time goes.

Myth

Python is named after the snake.

Fact

It is named after the British comedy group Monty Python. The snake logo came later.

Myth

AI models are written in Python, so Python does the maths.

Fact

Python describes the model and controls the training. The arithmetic itself runs in C, C++ and GPU code inside libraries.

Pro corner

Extra depth for experienced readers. New to this? Skip it for now and come back later.

  • ▸

    "Python" usually means CPython, the reference implementation written in C. Its C API is why the scientific stack exists: NumPy, pandas and PyTorch are C/C++ (and Rust, Fortran, CUDA) code exposed as Python modules. Topic 0.8 introduces implementations, and Topic 13.9 shows how extension modules work.

  • ▸

    Python's dominance in AI is partly a network effect. NumPy (2006) standardised the array, scikit-learn and the deep-learning frameworks built on that array interface, and every new tool chose Python because the others were there. A technically faster language would still have to rebuild that ecosystem.

  • ▸

    The interpreter is getting faster. Python 3.11 introduced a specialising adaptive interpreter that sped up typical code noticeably, 3.13 added an experimental just-in-time compiler and an experimental build without the global interpreter lock (the rule that lets only one thread run Python code at a time), and 3.14 made that free-threaded build officially supported. Phases 12 and 13 cover what these change in practice.

  • ▸

    In production AI systems Python is often the orchestration layer: it validates inputs, calls models, runs tools, handles retries and streams results. Those are I/O-bound jobs where interpreter speed matters little and clear, testable code matters a lot.

Remember this

  1. 1

    Python is a programming language created by Guido van Rossum and first released in 1991. It is free and open source: anyone may use it, read how it works and help improve it. It is looked after by the non-profit Python Software Foundation and a team of volunteer core developers. The name comes from the comedy group Monty Python, not the snake.

  2. 2

    Python is a high-level language: you write in terms close to human thinking ("add these numbers", "sort this list") and Python deals with the machine's details, such as where values live in memory. It is also general-purpose: the same language is used for websites, automation scripts, data analysis, scientific computing and AI.

  3. 3

    Python was designed to be readable. It uses plain English words (if, for, and, not, in) and uses indentation (spaces at the start of a line) to show structure, where many languages use curly braces and semicolons. A common saying among Python programmers is that code is read much more often than it is written.

  4. 4

    Python comes with "batteries included": a large standard library of ready-made tools for files, dates, maths, text, the internet and much more, installed along with the language. Beyond that, the Python Package Index (PyPI) hosts hundreds of thousands of free packages written by others, which you can install with one command (Phase 6).

  5. 5

    Why AI runs on Python. Training and running AI models means doing arithmetic on huge tables of numbers. Python itself is slow at raw arithmetic. Libraries such as NumPy and PyTorch do that work in fast compiled code: programs already translated into the instructions a processor runs directly (written in C or C++, or running on graphics chips called GPUs). Python is the readable layer on top that tells those libraries what to do. Researchers got quick experiments, engineers got fast execution, and over about fifteen years nearly every AI tool grew up with a Python interface first.

  6. 6

    What Python is not best at. Pure Python code is slower than languages such as C, Rust, Java or Go, often by a large factor when a program repeats a small calculation millions of times. Python is also rarely the choice for mobile apps, for code that runs inside a web browser page, or for operating-system kernels. Good engineers pick it where developer time matters more than raw speed, or where fast libraries do the heavy work.

Explain it without notes

01

What kind of language is Python? Describe it in three or four properties.

02

Why is Python the main language of AI even though it is slower than C or Java?

03

What does "batteries included" mean?

04

Name two kinds of software for which Python is usually not the first choice, and say why.

Practice

01

Write a program with a list of three temperatures, [31, 18, 25], that prints each temperature followed by warm if it is 25 or more and cool otherwise.

02

Using the standard library, print the average and the highest of the prices [120, 80, 100].

03

Without running it, say what this prints, then check: import math followed by print(math.sqrt(81)).

Trade-offs

  • ↔

    Developer speed vs run speed. Python lets you write and change code quickly but runs pure-Python code slower than compiled languages. This is a good trade when people's time costs more than computer time, or when libraries do the heavy work.

  • ↔

    Flexibility vs early error checking. Python does not make you declare the type of each value, so code is short, but some mistakes only show up when the line runs. Type hints (Phase 10) and tests (Phase 11) win much of that safety back.

  • ↔

    One language on top vs several underneath. The AI stack is easy to use because Python hides C, C++ and GPU code. The cost is that when something goes wrong deep inside, you may be debugging across language boundaries.

Done when you can

  • Done when you can describe Python in one or two sentences to a friend.

  • Done when you can explain why Python is used for AI although it is slower than C.

  • Done when you can name four areas where Python is used and two where it usually is not.

  • Done when you can say what the standard library and PyPI are.

  • Done when you have run import this and read the result.