Quantum Gates Explained with Code: X, H, Z, CNOT, SWAP, and More
quantum-gatescircuitscode-examplesbasicstutorial

Quantum Gates Explained with Code: X, H, Z, CNOT, SWAP, and More

SSmart Qubit Hub Editorial
2026-06-08
9 min read

A code-first guide to core quantum gates with practical examples in Qiskit, Cirq, and PennyLane.

If you are learning quantum computing for developers, gates are the point where the subject stops feeling abstract and starts becoming programmable. This guide explains the core quantum gates you will meet first, including X, H, Z, CNOT, SWAP, S, T, and common rotation gates, with code examples you can adapt in Qiskit, Cirq, and PennyLane. The aim is not to turn gate theory into dense mathematics. It is to give you a reusable mental model, a practical code pattern, and a set of examples you can revisit as SDKs evolve and your circuits become more ambitious.

Overview

A quantum gate is an operation applied to one or more qubits. In classical programming terms, it is tempting to think of a gate like a logical instruction. That comparison is useful up to a point, but it breaks down quickly because qubits can exist in superpositions and can become entangled. A gate changes the state of a qubit system according to the rules of quantum mechanics, and the order of gates matters.

For most practical beginner and intermediate work, you do not need to memorise full matrix forms before writing code. You do need to understand what each gate tends to do in a circuit, when it is commonly used, and what to expect when you measure at the end.

Here is the compact mental model:

  • X gate: flips |0⟩ to |1⟩ and |1⟩ to |0⟩. Think of it as the quantum analogue of a bit flip.
  • H gate: creates superposition from a basis state. It is often the first step in circuits that need branching probability.
  • Z gate: changes phase rather than measurement outcome directly. Its effect often becomes visible only when combined with other gates.
  • CNOT gate: conditional flip on a target qubit based on a control qubit. This is one of the basic ways to create entanglement.
  • SWAP gate: exchanges the states of two qubits. Useful when hardware connectivity or circuit layout matters.
  • S and T gates: phase gates used in many standard circuit constructions.
  • Rotation gates such as RX, RY, and RZ: parameterised gates that rotate the qubit state around an axis. These matter in variational circuits and quantum machine learning.

One important practical point: measurement only shows part of the story. Two circuits can produce the same measurement counts in one basis while having different internal phases. That is why gates like Z, S, T, and RZ can seem invisible until you combine them with interference-producing steps such as Hadamard gates.

If you are still setting up your local environment, it helps to start with a clean simulator workflow before testing on real devices. A useful companion is How to Install Qiskit, Cirq, and PennyLane: A Cross-Platform Setup Guide.

Template structure

The easiest way to learn quantum gates is to use the same repeatable structure for every experiment. Instead of jumping between one-off snippets, build each example with five steps:

  1. Define qubits
  2. Apply one or more gates
  3. Measure
  4. Run on a simulator
  5. Compare the result with your expectation

That pattern works across the major SDKs. The syntax changes, but the workflow stays familiar.

Reusable reasoning template

For each gate, ask the same questions:

  • What input state am I starting from?
  • Does this gate change amplitude, phase, or both?
  • Will the change be visible immediately at measurement, or only after interference with later gates?
  • Is this a single-qubit gate or a multi-qubit gate?
  • Does qubit order matter in this SDK?

Single-qubit example pattern

# Pseudocode
create 1 qubit
apply gate
measure
run simulator
inspect counts or statevector

Two-qubit example pattern

# Pseudocode
create 2 qubits
prepare control state if needed
apply two-qubit gate
measure both qubits
run simulator
inspect counts and qubit correlations

Qiskit pattern

from qiskit import QuantumCircuit
from qiskit_aer import AerSimulator

qc = QuantumCircuit(2, 2)
qc.h(0)
qc.cx(0, 1)
qc.measure([0, 1], [0, 1])

sim = AerSimulator()
result = sim.run(qc, shots=1024).result()
counts = result.get_counts()
print(counts)

Cirq pattern

import cirq

q0, q1 = cirq.LineQubit.range(2)
circuit = cirq.Circuit(
    cirq.H(q0),
    cirq.CNOT(q0, q1),
    cirq.measure(q0, q1, key='m')
)

simulator = cirq.Simulator()
result = simulator.run(circuit, repetitions=1024)
print(result.histogram(key='m'))

PennyLane pattern

import pennylane as qml
from pennylane import numpy as np

dev = qml.device('default.qubit', wires=2, shots=1024)

@qml.qnode(dev)
def circuit():
    qml.Hadamard(wires=0)
    qml.CNOT(wires=[0, 1])
    return qml.sample()

print(circuit())

If you are deciding which SDK to focus on first, compare developer ergonomics before going too deep into one stack. This related guide can help: Qiskit vs Cirq vs PennyLane: Which Quantum SDK Should You Learn First?.

How to customize

This is where quantum gates explained becomes genuinely useful rather than purely descriptive. The same gate can behave differently depending on your starting state, your measurement basis, and the surrounding circuit. Customising examples is the fastest way to build intuition.

X gate: the simplest state flip

The X gate maps |0⟩ to |1⟩. If you apply X to a qubit initialised in |0⟩ and then measure, you should get 1 every time in an ideal simulator.

# Qiskit
qc = QuantumCircuit(1, 1)
qc.x(0)
qc.measure(0, 0)
# Cirq
q = cirq.LineQubit(0)
circuit = cirq.Circuit(cirq.X(q), cirq.measure(q, key='m'))
# PennyLane
@qml.qnode(dev)
def circuit():
    qml.PauliX(wires=0)
    return qml.sample(wires=0)

Customize it by adding another X gate. Two X gates in sequence bring the qubit back to the original computational basis state. That teaches an important lesson: some gates are their own inverse.

H gate: the usual starting point for superposition

Apply H to |0⟩ and you should measure roughly half 0 and half 1 over many shots. This does not mean the qubit was partly 0 and partly 1 in a classical sense. It means the state was in superposition and measurement sampled from that state.

# Qiskit
qc = QuantumCircuit(1, 1)
qc.h(0)
qc.measure(0, 0)

Useful customization: apply H twice. Since H is its own inverse, H followed by H returns the qubit to |0⟩. This is one of the cleanest small experiments for testing your intuition.

Z gate: phase change without immediate visible flip

Beginners often ask why the Z gate seems to do nothing. If you apply Z directly to |0⟩ and measure in the computational basis, you still get 0. The important idea is that Z changes phase, not the measured bit value in that basis.

To see the effect, sandwich Z between Hadamards:

# Conceptually
|0⟩ --H--Z--H-- measure

This sequence behaves like X on |0⟩. It is a good reminder that phase becomes measurable through interference.

CNOT gate example: conditional logic and entanglement

The CNOT gate flips the target qubit only when the control qubit is in state |1⟩. If the control is |0⟩, nothing happens to the target. This makes CNOT a foundational gate in many quantum circuits.

Simple conditional example:

# Qiskit
qc = QuantumCircuit(2, 2)
qc.x(0)          # set control qubit to |1⟩
qc.cx(0, 1)      # flip target if control is 1
qc.measure([0,1], [0,1])

If qubit 0 starts as 1, the target flips from 0 to 1, so the output should be 11 in an ideal run.

Now the more important pattern: entanglement.

# Qiskit Bell state
qc = QuantumCircuit(2, 2)
qc.h(0)
qc.cx(0, 1)
qc.measure([0,1], [0,1])

You should see mostly 00 and 11, rather than all four outcomes equally. The qubits are correlated. This is one of the standard first examples in any quantum programming tutorial because it demonstrates something classically unfamiliar with very little code.

SWAP gate quantum example: moving information between qubits

SWAP exchanges the states of two qubits. If qubit 0 is |1⟩ and qubit 1 is |0⟩, a SWAP will exchange them.

# Qiskit
qc = QuantumCircuit(2, 2)
qc.x(0)
qc.swap(0, 1)
qc.measure([0,1], [0,1])

This is conceptually simple, but it matters in hardware-aware programming. On some devices, qubits are not fully connected, so swaps are inserted to move logical states across available connections. Even if you mostly work on simulators, understanding SWAP helps when circuit depth unexpectedly grows after transpilation or compilation.

S and T gates: small phase steps with large importance

S and T are phase gates. Their practical importance often appears in fault-tolerant discussions and circuit decompositions, but you do not need to start there. For now, treat them as controlled ways to alter phase.

A useful beginner experiment is:

|0⟩ --H--T--H-- measure

Then compare it with:

|0⟩ --H--Z--H-- measure

The outcomes differ because the phase change differs. These experiments help you see that not all phase gates have interchangeable effects.

Rotation gates: where practical quantum computing gets more flexible

RX, RY, and RZ gates rotate a qubit state by an angle. They are especially common in variational algorithms, hybrid quantum classical computing, and quantum machine learning workflows.

# PennyLane example
@qml.qnode(dev)
def circuit(theta):
    qml.RY(theta, wires=0)
    return qml.probs(wires=0)

Parameterized gates are worth revisiting often because they are central to modern quantum software stacks. If your work moves toward optimisation or ML-flavoured circuits, these gates become more useful than fixed textbook examples.

For simulator-focused learning paths, this companion guide is useful: Best Quantum Simulators for Developers: Features, Limits, and Free Tiers Compared.

Examples

Below are compact patterns you can keep as a working reference.

Example 1: Verify that X flips a basis state

  • Start: |0⟩
  • Gate: X
  • Expected measurement: always 1 on an ideal simulator

What to learn: a direct state flip is easy to test and easy to debug.

Example 2: Show that H creates a 50/50 outcome distribution

  • Start: |0⟩
  • Gate: H
  • Expected measurement: roughly even split between 0 and 1

What to learn: repeated shots matter; one measurement is not enough to infer the state.

Example 3: Reveal phase with HZH

  • Start: |0⟩
  • Gates: H, Z, H
  • Expected measurement: behaves like an X transformation on |0⟩

What to learn: phase can become visible through basis changes and interference.

Example 4: Build a Bell pair with H and CNOT

  • Start: |00⟩
  • Gates: H on qubit 0, then CNOT with qubit 0 as control
  • Expected measurement: mostly 00 and 11

What to learn: correlated outcomes are often the first sign that entanglement is present.

Example 5: Swap prepared states

  • Start: qubit 0 in |1⟩, qubit 1 in |0⟩
  • Gate: SWAP
  • Expected measurement: the states exchange positions

What to learn: qubit placement matters in realistic circuits.

Example 6: Sweep a rotation angle

  • Start: |0⟩
  • Gate: RY(θ)
  • Expected measurement: probability changes smoothly as θ changes

What to learn: parameterised circuits connect quantum programming to optimisation routines.

As you work through these examples, keep notes on three items: expected output, actual output, and your explanation for any mismatch. That simple habit turns a code exercise into a reusable debugging process.

When to update

This topic is worth revisiting because the core gate ideas stay stable while the surrounding tooling changes. If you treat this article as a living reference, update your working version when any of the following happens:

  • Your SDK syntax changes: method names, import paths, and simulator APIs may shift over time.
  • You move from simulators to hardware: noise, connectivity, and compilation become more important than ideal textbook behaviour.
  • You start using parameterised circuits: rotation gates and measurement choices matter more.
  • You need clearer team onboarding material: gate explanations should be tied to your chosen stack and coding standards.
  • You compare platforms: what looks simple in one SDK may be more verbose or more explicit in another.

A practical maintenance checklist:

  1. Re-run each code example after SDK upgrades.
  2. Check whether qubit ordering or measurement formatting differs across tools.
  3. Add one simulator screenshot or counts output for each example in your own notes.
  4. Expand the reference with controlled-Z, controlled-phase, and Toffoli once the basics feel routine.
  5. Document the same circuit in at least two SDKs to avoid tool-specific blind spots.

If your learning path broadens from gates to platforms and cloud access, these articles are useful next steps: What IonQ’s Stack Reveals About the Future of Quantum Cloud Access and The Quantum Vendor Map: Who Builds, Who Clouds, and Who Secures.

The most important takeaway is simple: do not try to memorise every gate as an isolated fact. Learn them as repeatable circuit behaviours. Start with basis flips, then superposition, then phase, then entanglement, then parameterised rotations. That sequence maps well to how most developers actually build intuition. If you return to this guide later, use it as a checklist: can you predict the output before you run the circuit, and can you explain why? When the answer is yes, the gates have become practical tools rather than abstract vocabulary.

Related Topics

#quantum-gates#circuits#code-examples#basics#tutorial
S

Smart Qubit Hub Editorial

Senior SEO Editor

Senior editor and content strategist. Writing about technology, design, and the future of digital media. Follow along for deep dives into the industry's moving parts.

2026-06-08T06:16:34.955Z