◆ AI All-in-One

Level 3 In-Depth AI · Reinforcement Learning

Reinforcement Learning: The Basics

How a machine learns by trial and error. An agent acts in an environment, collects rewards, and gradually learns which actions lead to the most reward over time.

Level
●●●●● Easy
Reading
14 min
To learn it well
1 hour to read, an afternoon to practise
↗ Plan a path here

Read first

Supervised, Unsupervised and Reinforcement Learning

This leads to

Multi-Armed Bandits and ExplorationMarkov Decision Processes
The full path from zero — 3 concepts before this one
  1. What Is AI?
  2. How Machines Learn
  3. Supervised, Unsupervised and Reinforcement Learning
  4. Reinforcement Learning: The Basics

Read them roughly in this order. See it on the concept map →

Why it matters

Most of machine learning learns from a fixed table of examples with the right answers attached. Supervised learning is told "this photo is a cat". But many problems have no answer key. Nobody can write down the correct move in every chess position, the right motor command for every instant of a robot's walk, or the perfect reply to every message. What we can do is say how well things went afterwards: you won, you fell over, the user liked the answer.

Reinforcement learning (RL) is learning from that kind of feedback. A learner acts, sees what happens, receives a score, and adjusts its behaviour so that, over time, it collects as much score as possible. It is how AlphaGo learned to beat the world's best Go players (Monte Carlo Tree Search and AlphaGo), how DeepMind's DQN learned dozens of Atari games from raw pixels (Deep Q-Networks), how robots learn to walk in simulation, and how chat models are polished to give answers people prefer (RLHF and Preference Optimization) or to reason step by step before answering (Reasoning Models and Test-Time Compute).

This chapter sets up the vocabulary and the one picture that every later RL chapter builds on. It uses a tiny gridworld, a board game simple enough to work out by hand, which we will reuse in Markov Decision Processes, Value Functions and Bellman Equations and Q-Learning.

The intuition

Think of training a dog. You can't explain to the dog what "sit" means. Instead, when it happens to sit, you give it a treat. When it jumps on the sofa, no treat. Over many tries the dog works out which behaviour earns treats in which situation. You never showed it the right answer. You only scored what it did.

Reinforcement learning has exactly this shape, and every piece has a name:

  • The agent is the learner and decision-maker: the dog, a game-playing program, a robot's controller.
  • The environment is everything outside the agent that it interacts with: the room and the owner, the game, the physical world.
  • A state is a description of the current situation: where the agent is, the board position, the robot's joint angles.
  • An action is a choice the agent can make: sit, move left, push the cart right.
  • A reward is a number the environment sends back after each action, saying how good that step was. Treat: +1. Nothing: 0. Fell into the pit: −1.
  • A policy is the agent's behaviour: a rule that says which action to take in each state. Learning means improving the policy.

These pieces interact in a loop. The agent looks at the state, picks an action, and the environment responds with a new state and a reward. Then it goes round again.

Agent follows a policy π(a | s) Environment the world: a game, a robot, a user action Aₜ "move up" state Sₜ₊₁ where am I now? reward Rₜ₊₁ how good was that? t ← t + 1, repeat until the episode ends goal: choose actions that make the total (discounted) reward as large as possible
Fig. 1 The agent–environment loop. At each time step the agent sees a state, chooses an action, and the environment answers with a reward and the next state.

Two things make this harder than it sounds.

  1. Delayed reward. The reward for a good move often comes much later. In chess only the final position is scored. So which of your 40 moves deserves the credit for the win? This is the credit assignment problem, and most of RL is clever ways of solving it.
  2. Exploration. The agent only learns about actions it actually tries. If it always repeats the first thing that worked, it may never discover something much better. It has to balance trying new things (exploring) against using what it already knows (exploiting). Multi-Armed Bandits and Exploration studies this trade-off on its own.

Key idea In reinforcement learning nobody gives the right action. The agent tries actions, receives rewards, and learns a policy that maximises the total reward it collects over time, not just the next one.

How it works

The loop, step by step

Time moves in discrete steps t=0,1,2,…t = 0, 1, 2, \dots. At each step:

  1. The agent observes the state StS_t.
  2. It chooses an action AtA_t.
  3. The environment returns a reward Rt+1R_{t+1} and a new state St+1S_{t+1}.

Capital letters mean these are random variables: they can come out differently each time. The notation follows the standard textbook, Sutton and Barto's Reinforcement Learning: An Introduction, and so does every RL chapter in this guide. Note that the reward that follows action AtA_t is written Rt+1R_{t+1}, not RtR_t. It arrives together with the next state, so it gets the next time index.

One run of the loop from a starting state to an end is an episode: one game of chess, one attempt to cross the grid. The state that ends it is a terminal state. The record of everything that happened is a trajectory:

S0,A0,R1,S1,A1,R2,S2,A2,R3,…S_0, A_0, R_1, S_1, A_1, R_2, S_2, A_2, R_3, \dots

Some tasks never end (a thermostat, a stock-trading agent). They are called continuing tasks, as opposed to episodic tasks.

The policy

The policy is written π\pi (the Greek letter "pi"; nothing to do with 3.14). Policies may be random. π(a∣s)\pi(a \mid s) is the probability that the agent picks action aa when it is in state ss. A deterministic policy always picks the same action in a given state. A random agent's policy gives each of four moves probability 0.25. Most RL algorithms learn a policy that starts nearly random and becomes more decisive as the agent learns.

The return: adding up future rewards

The agent's goal is not to grab the biggest next reward. It is to maximise the total reward from now on. That total is called the return, written GtG_t:

Gt=Rt+1+γRt+2+γ2Rt+3+⋯=∑k=0∞γkRt+k+1G_t = R_{t+1} + \gamma R_{t+2} + \gamma^2 R_{t+3} + \dots = \sum_{k=0}^{\infty} \gamma^k R_{t+k+1}

In words: the return at time tt is the next reward, plus the reward after that shrunk by a factor γ\gamma, plus the one after that shrunk by γ2\gamma^2, and so on. The Greek letter γ\gamma ("gamma") is the discount factor, a number between 0 and 1 that you choose.

Why shrink future rewards?

  • Sooner is better. With γ=0.9\gamma = 0.9 a reward of 1 that arrives 10 steps from now counts as 0.910≈0.350.9^{10} \approx 0.35 today. An agent that discounts prefers short routes to the goal.
  • It keeps sums finite. In a continuing task an undiscounted sum of rewards could grow forever. With γ<1\gamma < 1 it stays bounded.
  • The far future is uncertain. Rewards far ahead are less reliable, so trusting them less is sensible.

γ=0\gamma = 0 makes the agent short-sighted: only the next reward counts. γ\gamma close to 1 (0.99 is common) makes it far-sighted.

The return has a handy recursive form. Pull out the first reward and what's left is γ\gamma times the return from the next step:

Gt=Rt+1+γ Gt+1G_t = R_{t+1} + \gamma \, G_{t+1}

This one-line identity is the seed of the Bellman equations, the backbone of RL.

The reward hypothesis is the bet underneath the whole field: that every goal we care about can be expressed as maximising the expected return of a single scalar reward signal. It works remarkably often, and when it fails, it fails in interesting ways. Agents become very good at exploiting a badly designed reward, as reward hacking shows.

A gridworld walk-through

Here is the small world we will use throughout this part of the guide. It is a 4 × 4 board. The agent starts at the bottom-left. Each step it chooses up, down, left or right. Moving into the edge of the board or the grey wall leaves it where it is. Reaching the goal square (top-right) gives reward +1 and ends the episode. Falling into the pit just below the goal gives reward −1 and also ends it. Every other move gives reward 0. The discount is γ=0.9\gamma = 0.9.

goal reward +1 pit reward −1 wall start col 0 col 1 col 2 col 3 Any other move: reward 0 · discount γ = 0.9 Green path: 6 steps, ends at the goal rewards: 0, 0, 0, 0, 0, +1 G₀ = 0.9⁵ × (+1) = +0.59 Red path: 5 steps, falls in the pit rewards: 0, 0, 0, 0, −1 G₀ = 0.9⁴ × (−1) = −0.66 Random agent (1,000 episodes): average return −0.07, about 41 steps The agent's job: learn the green path from rewards alone, without a map.
Fig. 2 The 4 × 4 gridworld used across the RL chapters. The green path reaches the goal in 6 steps and earns a return of 0.59. The red path falls into the pit after 5 steps and earns −0.66.

Worked example 1: the green path. Up, up, up, right, right, right. The rewards are 0, 0, 0, 0, 0, +1. Only the last one is non-zero, and it arrives at the sixth step, so it is discounted five times:

G0=0+0.9⋅0+0.92⋅0+0.93⋅0+0.94⋅0+0.95⋅1=0.95≈0.590G_0 = 0 + 0.9 \cdot 0 + 0.9^2 \cdot 0 + 0.9^3 \cdot 0 + 0.9^4 \cdot 0 + 0.9^5 \cdot 1 = 0.9^5 \approx 0.590

Worked example 2: the red path. Right, right, up, right, up, and the agent lands in the pit. The rewards are 0, 0, 0, 0, −1, so

G0=0.94⋅(−1)≈−0.656G_0 = 0.9^4 \cdot (-1) \approx -0.656

Worked example 3: the recursion. One step into the green path, the agent stands one square up from the start, with five steps to go. Its return from there is G1=0.94=0.656G_1 = 0.9^4 = 0.656. Check the recursive form: G0=R1+γG1=0+0.9×0.656=0.590G_0 = R_1 + \gamma G_1 = 0 + 0.9 \times 0.656 = 0.590. ✓

Notice what discounting does. A longer route to the goal, say 10 steps, would earn only 0.99≈0.3870.9^9 \approx 0.387. So the agent has a reason to be quick even though no step costs anything.

What "learning" means here

The agent does not see this picture. It does not know where the pit is or that the wall exists. It only gets states and rewards, one step at a time. Learning means using that stream of experience to improve the policy, so that eventually it walks the green route every time.

There are three broad families of methods, and the rest of this part of the guide covers each:

In code

An environment is just an object with two methods. reset() starts an episode and returns the first state. step(action) applies an action and returns the next state, the reward, and whether the episode is over. Here is the gridworld, plus a loop that runs a policy and computes the discounted return.

import random

class GridWorld:
    """4x4 grid. Start bottom-left, goal top-right (+1), pit below it (-1)."""
    MOVES = {"up": (-1, 0), "down": (1, 0), "left": (0, -1), "right": (0, 1)}

    def reset(self):
        self.pos = (3, 0)
        return self.pos

    def step(self, action):
        dr, dc = self.MOVES[action]
        r, c = self.pos[0] + dr, self.pos[1] + dc
        if 0 <= r < 4 and 0 <= c < 4 and (r, c) != (1, 1):   # (1,1) is a wall
            self.pos = (r, c)
        if self.pos == (0, 3): return self.pos, +1.0, True   # goal
        if self.pos == (1, 3): return self.pos, -1.0, True   # pit
        return self.pos, 0.0, False

def run_episode(env, policy, gamma=0.9, max_steps=100):
    state, G, discount = env.reset(), 0.0, 1.0
    for t in range(max_steps):
        action = policy(state)
        state, reward, done = env.step(action)
        G += discount * reward          # G = R1 + γR2 + γ²R3 + ...
        discount *= gamma
        if done: break
    return G, t + 1

random.seed(0)
env = GridWorld()
random_policy = lambda s: random.choice(list(GridWorld.MOVES))
def sensible_policy(s):                 # up the left edge, then right
    return "up" if s[1] == 0 and s[0] > 0 else "right"

for name, pol in [("random", random_policy), ("sensible", sensible_policy)]:
    results = [run_episode(env, pol) for _ in range(1000)]
    avg_G = sum(g for g, _ in results) / len(results)
    avg_len = sum(n for _, n in results) / len(results)
    print(f"{name:9s} average return {avg_G:+.3f}  average length {avg_len:.1f} steps")

# random    average return -0.065  average length 40.8 steps
# sensible  average return +0.590  average length 6.0 steps

The random agent wanders for about 41 steps on average. It falls into the pit far more often than it finds the goal (about 690 times against 230 in these 1,000 episodes, with the rest timing out), but most of those endings come many steps in, so discounting shrinks them and its average return ends up just below zero. The hand-written policy scores 0.590 every time, exactly the number we worked out by hand. Every RL algorithm in the following chapters is a way of getting from the first line to the second without a human writing the policy.

The next step: Gymnasium

Real RL code uses Gymnasium, the standard Python library of environments (the maintained successor of OpenAI's Gym). Its interface is the one above with two refinements. reset also returns an info dictionary. step splits "done" into terminated (the task really ended, for example the pole fell) and truncated (a time limit cut the episode short). This snippet needs pip install gymnasium, so it isn't run here:

import gymnasium as gym

env = gym.make("CartPole-v1")             # balance a pole on a moving cart
obs, info = env.reset(seed=0)             # obs: 4 numbers (position, velocity, angle, angular velocity)
total = 0.0
for _ in range(500):
    action = env.action_space.sample()    # a random policy: 0 = push left, 1 = push right
    obs, reward, terminated, truncated, info = env.step(action)
    total += reward                       # +1 for every step the pole stays up
    if terminated or truncated:
        break
print("episode return:", total)           # a random policy usually lasts only a couple of dozen steps
env.close()

Swap "CartPole-v1" for "LunarLander-v3", "FrozenLake-v1" or an Atari game and the same loop works. Any agent you write against this interface can be tested on hundreds of environments.

Common pitfalls

  • Confusing reward with return. The reward is one step's score. The return is the discounted sum of all future rewards. An agent that maximised the next reward alone would happily walk past the goal to avoid a small cost now.
  • Off-by-one time indices. In this notation the reward for action AtA_t is Rt+1R_{t+1}. Libraries and papers differ (some write rtr_t). When you compute returns in code, check which reward goes with which action.
  • Badly designed rewards. The agent optimises exactly what you reward, not what you meant. A famous OpenAI demo (2016) showed a boat-racing agent that learned to circle forever collecting bonus targets instead of finishing the race, because the bonuses gave more points.
  • Too small a discount. With γ=0.5\gamma = 0.5 a reward 10 steps away is worth 0.510≈0.0010.5^{10} \approx 0.001, so the agent effectively can't see it. Long tasks need γ\gamma close to 1.
  • Treating truncated as terminated. When an episode is cut off by a time limit, the world didn't end. The agent could have kept collecting reward. Learning algorithms that treat a time-out as a true end learn biased values.

Watch out Reward design is where most real RL projects go wrong. If there is a loophole that scores well without doing the task, a good optimiser will find it. Watch what your agent actually does, not just the reward curve.

Where it leads

The gridworld problem has a precise mathematical form, the Markov decision process, covered in Markov Decision Processes. Once you have that, Value Functions and Bellman Equations shows how to compute the value of every square exactly when the rules are known, and Q-Learning shows how to learn the same thing purely from experience. Deep Q-Networks replaces the lookup table with a neural network so the idea scales to video games. Policy Gradients, Actor-Critic Methods and Proximal Policy Optimization learn the policy directly, and PPO is the algorithm behind classic RLHF and Preference Optimization. Monte Carlo Tree Search and AlphaGo and Model-Based RL and World Models add planning. Before any of that, Multi-Armed Bandits and Exploration isolates the exploration problem in its simplest setting.

A bit of history

RL has two roots. One is the psychology of animal learning: Edward Thorndike's "law of effect" (1911) said that behaviours followed by satisfaction become more likely. The other is optimal control. Richard Bellman's dynamic programming (1950s) gave the equations for planning when the rules are known. In 1959 Arthur Samuel's checkers program improved by playing against itself, an early ancestor of AlphaGo. In the 1980s Richard Sutton and Andrew Barto joined the two threads into the modern field. Sutton introduced temporal-difference learning (1988), and Chris Watkins introduced Q-learning (1989). Their textbook (first edition 1998, second edition 2018) is still the standard reference, and they received the 2024 Turing Award (announced in March 2025) for this work. In 1992 Gerald Tesauro's TD-Gammon reached near-expert backgammon by self-play. The modern era of deep RL began with DeepMind's Atari-playing DQN in 2013–2015 and AlphaGo in 2016.

Try it

  1. In the code, change gamma to 0.5 and to 0.99. How do the two average returns change? Why does the sensible policy's return depend on γ\gamma but not on luck?
  2. Write a policy that goes right first, along the bottom row, then up column 3. What happens, and why?
  3. Count how often the random agent reaches the goal versus the pit in 1,000 episodes.

Hint for 2: column 3 contains the pit, one square below the goal.

Check your understanding

4 quick questions. Pick an answer to see whether you were right and why. Your best score is saved on this device.

  1. An agent with γ = 0.9 reaches a goal worth +1 on its 4th step, with reward 0 on every earlier step. What is its return G₀?

  2. No step in the gridworld costs anything, yet a discounted agent still prefers a 6-step route to the goal over a 10-step one. Why?

  3. You design a boat-racing reward that gives points for hitting bonus targets. The agent learns to circle the targets forever and never finishes. What went wrong?

  4. An episode is cut off by a 500-step time limit while the agent is still doing fine. How should a learning algorithm treat that last state?

Finished this chapter?

Learn more

Hand-picked courses, books, videos and tutorials for going deeper. See all resources →

Course

Hugging Face Deep RL Course

Hugging Face · Intermediate · Free

A hands-on deep reinforcement learning course from Q-learning to PPO. You train agents in games.

Tutorial

Spinning Up in Deep RL

Joshua Achiam (OpenAI) · 2018 · Intermediate · Free

OpenAI's short, precise introduction to deep RL: key concepts and notation, the policy-gradient derivation, and clean reference implementations of VPG, PPO, DDPG, TD3 and SAC.

Course

UCL Course on Reinforcement Learning

David Silver · 2015 · Intermediate · Free

Ten recorded lectures with slides by the lead researcher behind AlphaGo. Covers MDPs, dynamic programming, TD learning, function approximation, policy gradients and planning; follows Sutton & Barto closely.

Docs

Gymnasium documentation

Farama Foundation · Beginner · Free

The standard Python API for RL environments (the maintained successor of OpenAI Gym): CartPole, LunarLander, Atari, MuJoCo and a tutorial on writing your own environment.

Article

A (Long) Peek into Reinforcement Learning

Lilian Weng · 2018 · Intermediate · Free

A dense, well-organised tour of the core ideas: MDPs, Bellman equations, dynamic programming, Monte Carlo and TD methods, Q-learning, DQN and policy gradients.

Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/rl/rl-basics.md