← Blog

Q-Learning Explained with a Simple Example

By Umar Shakar · 15 Nov 2026 · Artificial Intelligence

On this page

Most software follows rules that a developer wrote by hand. Reinforcement learning flips that around. You do not tell the program what to do. You tell it what counts as a good or bad outcome, and it works out the rules by trial and error.

Q-learning is the classic way to start with reinforcement learning. It is short enough to code in about 30 lines, yet it contains the ideas behind much bigger systems. In this guide I explain each piece in plain language, then train a tiny delivery robot in Python so you can see the numbers settle with your own eyes.

The situation: a robot that has never seen the building

Imagine a small delivery robot dropped into a corridor of an office building. It has a parcel to deliver. The customer's door is at one end of the corridor. At the other end is a staircase, which is the last place a wheeled robot should go. The robot does not know any of this. It can only move left or right, one spot at a time, and it gets feedback after each move.

You could hard-code "always go right". That works for this corridor, but not for the next building, or the next layout, or the day someone moves the door. What we want is a robot that learns the best behaviour from experience, wherever it is placed.

The building blocks of reinforcement learning

The aim is not to grab the biggest reward right now. It is to collect the largest total reward over the whole episode. That is what makes the problem interesting, because a small cost now can lead to a big gain later. Sutton and Barto's free textbook, Reinforcement Learning: An Introduction, is the standard reference for all of these terms.

What is a Q-table?

Q-learning keeps a table with one row per state and one column per action. Each cell holds a value written Q(s, a): the agent's current estimate of how much total future reward it will get if it takes action a in state s and behaves well afterwards.

At the start every cell is zero, because the robot knows nothing. As it moves around and collects rewards, the cells are updated. Once training is done, choosing what to do is easy: in each state, pick the action with the highest Q-value.

The Q-learning update rule

After every single move, the robot updates one cell using this rule:

Q(s, a) ← Q(s, a) + α × [ r + γ × max Q(s', a') − Q(s, a) ]

In plain words:

The method was introduced by Chris Watkins in his 1989 PhD thesis, and Watkins and Dayan later proved that, under certain conditions, it converges to the best possible values (Watkins & Dayan, 1992). Those conditions include trying every action in every state many times and reducing the learning rate in a suitable way over time.

Learning rate (alpha)

Alpha, between 0 and 1, controls how big each nudge is. With alpha = 1 the robot throws away its old estimate and trusts only the latest experience. With a tiny alpha it learns very slowly but is less thrown by one lucky or unlucky move. I use 0.5 in the example because the corridor never changes.

Discount factor (gamma)

Gamma, also between 0 and 1, decides how much the robot cares about future rewards. A gamma of 0 makes it short-sighted: only the next reward matters. A gamma close to 1 makes it patient. With gamma = 0.9, a reward of 10 that is one step away is worth 9 today, two steps away it is worth 8.1, and so on.

Exploration vs exploitation: epsilon-greedy

If the robot always picks the action with the highest Q-value, it may lock onto the first thing that worked and never find something better. If it always acts randomly, it never uses what it has learned. This tension is called the exploration vs exploitation trade-off.

The simplest fix is epsilon-greedy. With a small probability epsilon (say 0.2), the robot picks a random action and explores. The rest of the time it exploits its best known action. In longer projects, people often start with a high epsilon and lower it as training goes on, so the agent explores early and settles down later.

Q-learning example in Python

Here is the full corridor example. Positions 0 (stairs) and 5 (customer's door) end the episode, and the robot always starts at position 2. The code uses only Python's standard library, so there is nothing to install. A fixed random seed makes the output repeatable.

import random

random.seed(7)

# A corridor with 6 spots: 0 = stairs (bad), 5 = customer's door (goal)
N_STATES, START = 6, 2
ACTIONS = ["left", "right"]

def step(state, action):
    nxt = state - 1 if action == "left" else state + 1
    if nxt == 5:
        return nxt, 10, True     # parcel delivered
    if nxt == 0:
        return nxt, -10, True    # robot rolled towards the stairs
    return nxt, -1, False        # every ordinary move costs a little battery

alpha, gamma, epsilon = 0.5, 0.9, 0.2
Q = {(s, a): 0.0 for s in range(N_STATES) for a in ACTIONS}

for episode in range(200):
    state, done = START, False
    while not done:
        if random.random() < epsilon:
            action = random.choice(ACTIONS)                      # explore
        else:
            action = max(ACTIONS, key=lambda a: Q[(state, a)])   # exploit
        nxt, reward, done = step(state, action)
        best_next = 0 if done else max(Q[(nxt, a)] for a in ACTIONS)
        Q[(state, action)] += alpha * (reward + gamma * best_next - Q[(state, action)])
        state = nxt

for s in range(1, 5):
    print(s, {a: round(Q[(s, a)], 2) for a in ACTIONS})
print("Policy:", [max(ACTIONS, key=lambda a: Q[(s, a)]) for s in range(1, 5)])

Expected output:

1 {'left': -9.38, 'right': 4.58}
2 {'left': 3.12, 'right': 6.2}
3 {'left': 4.58, 'right': 8.0}
4 {'left': 6.2, 'right': 10.0}
Policy: ['right', 'right', 'right', 'right']

Reading the results

The learned policy is "go right" in every position, which is exactly what we wanted. The numbers also make sense if you work them out by hand. From position 4, moving right reaches the door for +10, so Q(4, right) = 10. From position 3, moving right costs -1 and then lands where the best value is 10, so Q(3, right) = -1 + 0.9 × 10 = 8. From position 2 it is -1 + 0.9 × 8 = 6.2. The robot has worked out the true values without ever being told where the door was.

Notice Q(1, left) is close to -10, not exactly -10. The robot rarely chose that move after it learned it was bad, so the estimate is still settling. That is normal: Q-learning is most accurate for the actions the agent actually takes often.

When reinforcement learning beats rule-based systems

Rules are cheaper, easier to test and easier to explain. If you can write the rules down, write them down. Reinforcement learning earns its place when:

A good example from the web world is an online store deciding which products to show next. A fixed rule such as "show best sellers" is easy, but a learning system can test which suggestions lead to purchases over a whole visit, not just the next click. The catch is that a reward based only on clicks can reward the wrong thing and feed popularity loops. I wrote about that risk in my post on bias in recommendation systems.

Tips if you try this yourself

Key takeaways

Frequently asked questions

What is Q-learning in simple terms?

It is a trial-and-error method where an agent keeps a score for every action in every situation, and improves those scores each time it sees what happens next.

What does the Q in Q-learning stand for?

It is usually read as "quality": Q(s, a) measures how good it is to take action a in state s.

Is Q-learning supervised learning?

No. There are no labelled correct answers. The agent only receives rewards, which tell it how good an outcome was, not what it should have done.

What is a good value for epsilon?

Values between 0.05 and 0.2 are common starting points. Many projects begin higher and decay epsilon over time so the agent explores early and exploits later.

If you are thinking about adding smarter, data-driven features to your website or store, take a look at my web development and SEO services. If you want to get comfortable with the Python used here first, read my introduction to Python.

Need a website, SEO or a custom business app?
I'm Umar, a web developer and SEO specialist in Abu Dhabi. Get in touch.