AI news
AI model reviews
AI tools
How-to guides
Our staffAboutContact

How to code AI: a beginner's guide with two worked Python examples

How to code AI from scratch: install Python, train your first model with scikit-learn, and use AI assistants to explain and improve your code.

Monitor showing lines of programming code
Photo: Ilya Pavlov on Unsplash

To code AI as a beginner, you install Python, add a free machine learning library called scikit-learn, give it labelled examples and let it learn a pattern it can apply to new data. That's how most small AI programs start. You can also use AI to write code for you, and I'd do both at once: build the model yourself, and ask an AI assistant when you get stuck.

By the end of this guide you'll have a tiny working AI that reads a short film review and says whether it's positive or negative, in about 30 minutes. A second, slightly bigger example sorts text messages into spam and normal mail. You don't need a maths degree for any of it (you'll want some maths later, but not today).

If you'd like the background first, our explainer on what AI is covers the basics, and AI vs traditional programming shows why learned code behaves differently from rules you type by hand.

Before you start: the kit you need

  • A computer running Windows, macOS or Linux. An ordinary laptop is plenty for this guide.
  • Python 3. The releases still getting bug fixes on python.org are 3.15 and 3.14.
  • A code editor. Any plain text editor works, though most beginners seem to settle on VS Code, which is free.
  • About 30 minutes and a terminal window you're not scared of.
  • Optional: an AI chatbot or GitHub Copilot to explain errors. Copilot's free plan includes 2,000 code completions a month.

Tip: Copy every code box exactly. Python cares about spelling, capital letters and brackets, so pasting beats retyping.

Step 1: Decide which kind of AI coding you mean

The phrase covers two different jobs. When people ask how to code an AI, they usually mean writing a program that learns from data. When they ask how to use AI for coding, they mean getting a chatbot or assistant to write the code for them.

This guide does the first and uses the second as a helper. Spam filters, film recommendations and photo tagging all run on the same basic idea as the program you're about to write; chatbots such as ChatGPT are vastly bigger versions trained on huge amounts of text, and our guide to LLM AI explains how those work.

You should now know which goal you're after. If it's only the second, jump to Step 6.

Step 2: Install Python

Open the Python downloads page and grab the installer for your system. I'd pick Python 3.14 over the brand-new 3.15. It's had a year of fixes, and add-on libraries sometimes take a little while to catch up with a fresh release.

On Windows, tick the box that adds Python to PATH before you click Install. Easy to miss. Then open a terminal (PowerShell on Windows, Terminal on a Mac) and type:

python --version

You should see something like "Python 3.14.10". On a Mac, try python3 --version if plain python isn't found.

Step 3: Create a project folder and a virtual environment

A virtual environment is a private box for one project's libraries, so they don't clash with anything else on your computer. scikit-learn's install guide calls it optional but "strongly recommended", and I agree with that, because it heads off a whole family of confusing errors later.

Make a folder called my-first-ai, open your terminal inside it, and run these three lines one at a time. On Windows:

python -m venv ai-env
ai-env\Scripts\activate
pip install -U scikit-learn

On macOS or Linux, use these instead:

python3 -m venv ai-env
source ai-env/bin/activate
pip install -U scikit-learn

You should now see (ai-env) at the start of your terminal line. The last command installs scikit-learn (version 1.9.1 right now) plus the number libraries it depends on.

Step 4: Gather labelled examples

Machine learning means the program works out its own rules from examples. You don't write "if the review contains awful, call it negative"; the model figures that out. So you need data, and each example needs the right answer attached, which is called a label.

Here, the data is six one-line film reviews, each marked positive or negative. Six is laughably small. Real projects use thousands or millions of rows, and our explainer on AI datasets covers where those come from. Still, a tiny set lets you see every moving part on one screen, which I think matters more than accuracy on day one.

Step 5: Write and train your first model

Create a file called first_ai.py in your folder and paste this in:

from sklearn.feature_extraction.text import CountVectorizer
from sklearn.naive_bayes import MultinomialNB
from sklearn.pipeline import make_pipeline

texts = ["I loved this film", "What a great story", "Brilliant acting and a fun plot", "I hated every minute", "Boring and far too long", "The worst film this year"]
labels = ["positive", "positive", "positive", "negative", "negative", "negative"]

model = make_pipeline(CountVectorizer(), MultinomialNB())
model.fit(texts, labels)

print(model.predict(["What a fun film", "Too long and boring"]))

Each part does one job:

  1. The three import lines load tools from scikit-learn.
  2. texts holds the reviews and labels holds the right answers, in the same order.
  3. CountVectorizer turns each review into word counts, since the model can only read numbers.
  4. MultinomialNB is a Naive Bayes classifier, which learns how often each word turns up in positive and negative reviews.
  5. fit is the training step, and predict asks the trained model about reviews it has never seen.

Run it with python first_ai.py. You should see ['positive' 'negative'] printed in the terminal. That's a trained model, used on new text, in eleven lines.

Step 6: Ask an AI assistant to explain or extend your code

This is where using AI to write code comes in. Open whichever chatbot you like (ChatGPT, Claude, Gemini and Copilot Chat should all cope with this) and paste a prompt like this one, followed by your code:

I'm a beginner learning Python. Below is my first machine learning script. Explain each line in everyday words. Then suggest one small change that would make the model more accurate, and tell me why it helps. Don't rewrite the whole script.

Read the explanation before you accept any change. If you'd rather have help inside your editor, Copilot's free plan works in VS Code, and the Pro plan is $10 a month for unlimited completions. Our list of free AI coding assistants compares other options if Copilot isn't your thing.

Watch out: AI assistants sometimes invent function names or settings that don't exist. When code they wrote throws an error, paste the full error message back and ask what went wrong, rather than guessing.

Step 7: Test it on harder sentences

Swap the last line of first_ai.py for this and run the file again:

print(model.predict(["Not great, I hated it", "This film was not boring at all"]))

With this training set, the model calls the first review positive and the second negative. Both wrong. It only counts words, so "great" drags the first towards positive and "boring" pulls the second down, whatever "not" is doing in the sentence. Honestly, I like this failure: it shows you exactly what the model does and doesn't understand, which most tutorials skip.

You should now have a model you can break on purpose. That's progress.

Example: a complete spam filter from start to finish

Time to put every step together in one small project. Goal: a script that asks you for a text message and says whether it looks like spam or a normal message (usually called "ham"). You'll reuse the folder and virtual environment from Step 3, so there's nothing new to install.

First, create spam_filter.py and paste in the import lines and the training data. Six normal messages, six spam:

from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import make_pipeline

messages = ["Are we still on for lunch tomorrow?", "Can you send me the notes from class?", "Running ten minutes late, sorry", "Happy birthday! Hope you have a great day", "Did you feed the cat this morning?", "See you at the station at six", "WIN a free iPhone now, click this link", "Congratulations, you have won a cash prize", "URGENT: your account is locked, verify your password here", "Claim your free gift card today only", "You have been selected for a cash reward, reply YES", "Cheap loans approved instantly, click now"]
labels = ["ham"] * 6 + ["spam"] * 6

Then paste the model underneath. It uses two different tools from scikit-learn: TfidfVectorizer, which gives rare words more weight than common ones, and LogisticRegression, a basic classifier that also reports how confident it is.

model = make_pipeline(TfidfVectorizer(), LogisticRegression())
model.fit(messages, labels)

new_message = input("Type a message: ")
print("This looks like:", model.predict([new_message])[0])
print("Confidence:", round(model.predict_proba([new_message]).max(), 2))

Next, run python spam_filter.py and type "Click here to claim your free prize" when it asks. You should see "This looks like: spam" with a confidence of about 0.63. Run it again with "Can we move lunch to Friday?" and it should say ham, at roughly 0.57.

Those confidence scores are low, and that's the honest lesson of the example. Twelve messages can't teach a model much. It's picked up that "free", "click" and "cash" mean trouble, so a fake parcel text ("Your parcel is waiting, click to pay the fee") still gets flagged as spam, but only barely, at around 0.55.

Finally, grow it. Add 20 more real messages of each kind to the list (from your own phone, with anything private removed), keeping all the normal messages first and the spam after them. Change both 6s in the labels line to 26, run the script again, and the confidence numbers should climb. Then paste the script into your AI assistant with this prompt:

This is my spam filter in Python using scikit-learn. Show me how to hold back 25% of the messages as a test set with train_test_split and print the accuracy score. Keep my variable names and explain each new line.

You've now built, tested and improved a working text classifier, which is the same loop real teams follow, just on a much larger scale.

Common mistakes and fixes

"No module named sklearn"

This almost always means your virtual environment isn't switched on. Run the activate line from Step 3 again, check that (ai-env) appears, then retry. Also make sure you installed scikit-learn: the old package called plain "sklearn" on PyPI is deprecated, and its own summary line says to use scikit-learn instead.

"Found input variables with inconsistent numbers of samples"

Your texts and labels lists have different lengths. Count them. Every example needs exactly one label, in the same position.

Testing on the training data

If you check accuracy on the same examples you trained on, the score looks far better than it really is. Keep some data back for testing, as the last prompt in the worked example shows.

Trusting AI-written code without reading it

It's tempting to paste whatever the chatbot returns and move on. Don't. Ask it to explain anything you can't follow, and run the code after each small change so you know which change broke things.

Tips to get better results

  • Get more data before you change the model. More examples probably help a beginner project more than any clever setting will.
  • Keep your labels balanced, roughly the same number of each class, or the model may lean towards whichever answer it saw most.
  • Change one thing at a time and write down the result, so you know what actually helped.
  • Give your AI assistant context: your Python version, the library, the full error and what you expected to happen.
  • Read scikit-learn's getting started page once you've finished here; it uses the same fit and predict pattern you've just learned.

Next steps

Once both examples run, you've got the core loop down: data, train, predict, check. From here I'd pick one direction rather than three. If you enjoy the modelling side, a structured course gives you the maths and theory in order, and our pick of AI courses for beginners plus our guide to free AI courses are good places to compare options. If you're more drawn to building tools on top of big language models, read about agentic AI next, since that's where a lot of beginner projects seem to end up.

And keep your two scripts. They're tiny, but you'll likely come back to them when a bigger project stops making sense.

FAQ

How to program AI?

Install Python, set up a virtual environment and add a library such as scikit-learn. Collect labelled examples, train a model with fit, then test it with predict on data it hasn't seen. A small text classifier is a sensible first project.

How to code an AI?

You code an AI by writing a program that learns rules from examples instead of following rules you typed. In Python, that's often fewer than 15 lines with scikit-learn: load your data, pick a model, call fit to train it and predict to use it. The hard part is usually getting good data, and I'd expect to spend more time cleaning examples than writing code, at least for your first few projects.

How to use AI for coding?

Paste your code or error into a chatbot such as ChatGPT or Claude and ask it to explain, fix or extend it. Inside your editor, GitHub Copilot's free plan gives you 2,000 completions a month. Read every suggestion first; assistants can invent functions.

How does an AI work?

Most modern AI learns patterns from lots of examples. During training, it adjusts internal numbers until its guesses match the right answers as closely as possible. Afterwards, it applies those learned patterns to new inputs. A spam filter learns which words signal spam; a chatbot learns which words tend to follow others across huge amounts of text. Neither one understands meaning the way you do, which is why both can be fooled.

How does AI work at a basic level?

At a basic level, AI turns input such as text or images into numbers, runs them through a model and outputs a prediction. The model's settings come from training on examples, not hand-written rules. The film review classifier in Step 5 does exactly that, with six examples instead of millions.

Keep reading