Ready to write your first quantum program? In this tutorial, we will use Qiskit, the open-source Python SDK developed by IBM, to build a basic quantum circuit that creates a Bell State (a perfectly entangled state of two qubits).
Let's get started.
Prerequisites
Ensure you have Python installed (version 3.10 or higher is recommended). You can install Qiskit usingpip from your terminal:
pip install qiskit qiskit-aer
qiskit is the core SDK.
qiskit-aer is the high-performance local simulator package.
Step 1: Initialize the Circuit
We will create a quantum circuit with two qubits and two classical bits. The classical bits are used to store the results of measuring the qubits.Create a new Python file named bell_state.py and add the following imports:
from qiskit import QuantumCircuit
from qiskit_aer import AerSimulator
Create a Quantum Circuit acting on 2 qubits and 2 classical bits
qc = QuantumCircuit(2, 2)
Step 2: Apply Quantum Gates
To entangle our two qubits, we need to perform two steps:- Put the first qubit (qubit 0) into superposition. We do this using a Hadamard (H) Gate.
- Entangle the two qubits. We do this using a Controlled-NOT (CNOT) Gate where qubit 0 is the control and qubit 1 is the target.
# Apply a Hadamard gate to qubit 0
qc.h(0)
Apply a CNOT gate with control qubit 0 and target qubit 1
qc.cx(0, 1)
Step 3: Add Measurement
Now, we must measure our qubits. The measurement collapses the quantum state into a classical 0 or 1, which we store in the classical bits.# Measure both qubits into the classical bits
qc.measure([0, 1], [0, 1])
Step 4: Simulate the Circuit
We will use Qiskit Aer'sAerSimulator to run this circuit 1,024 times. Since the qubits are entangled, we expect to measure either 00 or 11 roughly 50% of the time each. We should almost never see 01 or 10.
# Initialize the simulator
simulator = AerSimulator()
Run the circuit on the simulator
job = simulator.run(qc, shots=1024)
Get the results
result = job.result()
counts = result.get_counts()
print("Measurement Counts:", counts)
Run the Code
Execute the script in your terminal:python bell_state.py
You should see output similar to this:
Measurement Counts: {'00': 507, '11': 517}
As expected, the qubits collapsed into the same state almost every time, proving they were entangled. Congratulations. You have successfully programmed and simulated your first quantum circuit.
Share this article
Comments & Discussion
Giscus comments frame aggregates active developer discussions linked to our GitHub repository.