First time studying this topic?

Launch the interactive walkthrough to discover each component, including the 3D Q-Sphere Lab & Python in Colab.

Topic 6.11

Building Quantum Circuits in Code: Qiskit Syntax

Construct, manipulate, and compile quantum circuits using industry-standard Python frameworks (Qiskit QuantumCircuit API).

Learning Objectives

  • ✓Construct QuantumCircuit objects with QuantumRegister and ClassicalRegister
  • ✓Attach single- and two-qubit gates: qc.h(), qc.x(), qc.cx()
  • ✓Compile circuits and generate OpenQASM 2.0/3.0 assembly code

📖Let's Begin with a Story

In 2017, an IBM research team led by Jay Gambetta open-sourced Qiskit (Quantum Information Science Kit). Before Qiskit, if you wanted to run a quantum algorithm on IBM's 5-qubit cloud chip, you had to write raw machine pulses or low-level assembly. Qiskit introduced an object-oriented Python API that made building quantum circuits as natural as writing standard Python: ``python qc = QuantumCircuit(2, 2) qc.h(0) qc.cx(0, 1) qc.measure([0, 1], [0, 1]) `` Today, Qiskit is the most widely used quantum programming framework in the world, downloaded millions of times and supported across academic and enterprise research.

Why Should You Learn Building Quantum Circuits in Code: Qiskit Syntax?

🎯 Practical & Engineering Stakes

The industry programming standard

Writing clean Qiskit code is the primary technical skill evaluated in quantum computing developer interviews and research collaborations worldwide.

What Is It?

Simple Explanation

Building a quantum circuit in Python: 1. qc = QuantumCircuit(2, 2): Create a circuit with 2 qubits and 2 classical bits. 2. qc.h(0): Put qubit 0 into superposition! 3. qc.cx(0, 1): Entangle qubit 0 and qubit 1 with a CNOT gate! 4. qc.measure_all(): Measure all qubits! 5. Send to a simulator or real IBM quantum computer to run!

Technical Explanation

The Qiskit QuantumCircuit class represents an internal directed acyclic graph (DAGCircuit) of quantum operations. Methods like qc.h(q), qc.cx(c, t), and qc.append(gate, qargs) append CircuitInstruction nodes to the DAG. Circuits serialize to standard OpenQASM intermediate representation for compiler passes and hardware transpilation.

📚 Key Terms

QuantumCircuitQuantumCircuit

Simple: The master Python object used to construct quantum programs in Qiskit.
Technical: Core class in qiskit.circuit representing a quantum program composed of registers, gates, and instructions.

OpenQASMOpenQASM

Simple: The assembly language of quantum computers (like machine code for qubits).
Technical: Quantum Assembly Language (OpenQASM 3.0) intermediate representation for quantum circuits.

TranspilationTranspilation

Simple: Rewriting your high-level quantum circuit so it matches the specific layout and native gates of a real physical chip.
Technical: Compilation pass mapping abstract circuits to hardware-native coupling graphs and basis gate sets while minimizing circuit depth.

Q-Sphere Lab: Building Quantum Circuits in Code: Qiskit Syntax

IBM Q-Sphere Model

Interactive 3D state vector exploration, unitary transformation gates, and Born rule collapse for Topic 6.11

Azimuth: 45°Elevation: 25°
+Z |0⟩-Z |1⟩+X |+⟩+Y |+i⟩01|ψ⟩
Q-Sphere Phase Color:
0 π/2 π 3π/2

Quantum Statevector

dim(H) = 2
|ψ⟩ = (1.000 + 0.000i)|0⟩
     + (0.000 + 0.000i)|1⟩
Polar Angle (θ):0.0° (0.000π rad)
Phase Angle (ϕ):0.0° (0.000π rad)

Born Rule Probabilities: P(x) = |⟨x|ψ⟩|²Σ P = 1.00

P(|0⟩) = |α|²100.0%
P(|1⟩) = |β|²0.0%
Quantum Measurement

Apply Single-Qubit Unitary Gates

Presets:
Continuous Polar Angle θ (0° = |0⟩, 180° = |1⟩):0.0°
Continuous Phase Angle ϕ (0° to 360°):0.0°
Recent Operations Log:
#1Initial state: |0⟩

📐 Mathematical Foundation

LaTeX KaTeX
Depth(C)≤Gates(C),Texecution=∑l=1Depthmax⁡g∈lτ(g)\text{Depth}(C) \le \text{Gates}(C), \quad T_{\text{execution}} = \sum_{l=1}^{\text{Depth}} \max_{g \in l} \tau(g)

What does it mean?

Quantum Circuit Depth & Physical Execution Time: In quantum circuit programming (Qiskit), "Depth" is the number of parallel time slices (layers) required to run the circuit. Gates operating on independent qubits execute simultaneously in parallel. Total runtime must remain strictly less than the qubit decoherence time T2.

Understanding the Symbols

Symbol / TermMeaningBeginner Interpretation
CCQuantum circuit object (QuantumCircuit)The program structure containing qubits, gates, and classical registers
Depth(C)\text{Depth}(C)Circuit depth (time slices)Longest sequence of dependent gates along any single qubit wire
Gates(C)\text{Gates}(C)Total gate countTotal number of quantum gate operations in the circuit
τ(g)\tau(g)Physical gate durationTime needed by microwave pulse (single-qubit gate ≈20\approx 20 ns, CNOT ≈200\approx 200 ns)

📊 Numerical Example

Analyzing depth and execution duration for a 2-qubit circuit with H on q0, H on q1, then CNOT(q0 → q1):

Step 1: Layer 1 (Parallel Gates): H applied to q0 AND H applied to q1 simultaneously. Layer 1 time = max(20 ns, 20 ns) = 20 ns Step 2: Layer 2 (Entangling Gate): CNOT applied across q0 and q1. Layer 2 time = 200 ns Step 3: Metrics: Total Gate Count = 1 + 1 + 1 = 3 gates Circuit Depth = 2 layers (Layer 1 + Layer 2) Total Runtime = 20 ns + 200 ns = 220 ns (0.22 μs)

Result: Because 220 ns is far less than typical coherence time T2 ≈ 100 μs, the circuit executes with high fidelity.

⚙️ How Does It Work?

1

Circuit Instantiation

Define qubit and bit counts: qc = QuantumCircuit(2, 2).

2

Gate Appending

Call gate methods sequentially: qc.h(0), qc.x(1), qc.cx(0, 1).

3

Measurement Mapping

Map quantum registers to classical bits: qc.measure(0, 0).

🌍 Where Is It Used?

Cloud Quantum Execution

Problem: Submitting a quantum circuit from a laptop in London to run on a dilution refrigerator in Yorktown Heights, New York.

Solution: Qiskit Runtime serializes the QuantumCircuit and streams measurement counts back over secure HTTPS.

🎯 Try It Yourself

In Qiskit, what code attaches a CNOT gate with qubit 0 as control and qubit 1 as target?

Interactive activity component

🐍 Python Hands-On: Building and Drawing a 3-Qubit GHZ State Circuit in Qiskit

Construct an industry-standard 3-qubit Greenberger-Horne-Zeilinger (GHZ) state circuit in Qiskit and inspect its structure.

Open Colab

1Install Required Packages

For Google Colab or Jupyter notebooks, run this shell command to install the required dependencies:

Terminal / Notebook Install Commandbash
!pip install qiskit
Packages:
qiskit

2Import Libraries

Import Statementspython
1from qiskit import QuantumCircuit
2from qiskit.quantum_info import Statevector

from qiskit import QuantumCircuit → Circuit module

from qiskit.quantum_info import Statevector → Statevector module

3Demonstration Code & Logic

Python Execution Codepython
1# Build a 3-Qubit GHZ State: (|000> + |111>)/sqrt(2)
2qc = QuantumCircuit(3, 3)
3qc.h(0) # Superposition on qubit 0
4qc.cx(0, 1) # Entangle q0 with q1
5qc.cx(1, 2) # Entangle q1 with q2
6qc.measure([0, 1, 2], [0, 1, 2])
7print('=== 3-Qubit GHZ State Circuit Diagram ===')
8print(qc.draw('text'))
9
10# Analyze Statevector before measurement
11qc_no_meas = qc.remove_final_measurements(inplace=False)
12sv = Statevector.from_instruction(qc_no_meas)
13print('\nNon-zero basis state probabilities:')
14for state, prob in sv.probabilities_dict().items():
15 if prob > 0.01:
16 print(f' |{state}> : {prob * 100:.1f}%')
Step-by-Step Code Breakdown:

# Build a 3-Qubit GHZ State: (|000> + |111>)/sqrt(2)

GHZ circuit

qc = QuantumCircuit(3, 3)

3 qubits and 3 classical bits

qc.h(0) # Superposition on qubit 0

Step 1: H on q0

qc.cx(0, 1) # Entangle q0 with q1

Step 2: CNOT q0->q1

qc.cx(1, 2) # Entangle q1 with q2

Step 3: CNOT q1->q2

qc.measure([0, 1, 2], [0, 1, 2])

Measure all 3 qubits

print('=== 3-Qubit GHZ State Circuit Diagram ===')

Header

print(qc.draw('text'))

Print text diagram

# Analyze Statevector before measurement

Statevector analysis

qc_no_meas = qc.remove_final_measurements(inplace=False)

Strip measurement

sv = Statevector.from_instruction(qc_no_meas)

Compute statevector

print('\nNon-zero basis state probabilities:')

Label

for state, prob in sv.probabilities_dict().items():

Print probabilities

if prob > 0.01:

Filter non-zero

print(f' |{state}> : {prob * 100:.1f}%')

Show 50% |000> and 50% |111>

📋 Complete Script (All-in-One)

Click "Copy for Colab", open Google Colab, paste into a single cell, and run.

Google Colab Notebook Scriptpython
1# =========================================================
2# Building and Drawing a 3-Qubit GHZ State Circuit in Qiskit
3# Prepared for Google Colab (Run with Shift + Enter)
4# =========================================================
5
6# Step 1: Install required packages
7!pip install qiskit
8
9# Step 2: Import libraries
10from qiskit import QuantumCircuit
11from qiskit.quantum_info import Statevector
12
13# Step 3: Run Demonstration
14# Build a 3-Qubit GHZ State: (|000> + |111>)/sqrt(2)
15qc = QuantumCircuit(3, 3)
16qc.h(0) # Superposition on qubit 0
17qc.cx(0, 1) # Entangle q0 with q1
18qc.cx(1, 2) # Entangle q1 with q2
19qc.measure([0, 1, 2], [0, 1, 2])
20print('=== 3-Qubit GHZ State Circuit Diagram ===')
21print(qc.draw('text'))
22
23# Analyze Statevector before measurement
24qc_no_meas = qc.remove_final_measurements(inplace=False)
25sv = Statevector.from_instruction(qc_no_meas)
26print('\nNon-zero basis state probabilities:')
27for state, prob in sv.probabilities_dict().items():
28 if prob > 0.01:
29 print(f' |{state}> : {prob * 100:.1f}%')
⚡ How to Run in Google Colab (3 Quick Steps)
  1. Click "Copy for Google Colab" above.
  2. Click Open New Google Colab Notebook (opens in a new tab).
  3. Click on the first empty code cell, press Ctrl + V (or Cmd + V) to paste, then press Shift + Enter to execute!

🔄 Algorithmic Execution Flow

1
Hadamard on Seed Qubit

Initialize superposition on qubit 0.

→
2
Cascade CNOT Gates

Propagate entanglement through qubits 1 and 2 to create tripartite correlation.

→
3
Simulate & Draw

Inspect circuit diagram and verify non-local 3-qubit superposition (|000> + |111>)/sqrt(2).

📥 Input / Initial State
QuantumCircuit(3, 3) implementing GHZ state.
📤 Expected Output
q_0: ──[ H ]──■──────────────[ M ]
              │              ║
q_1: ─────────X────■─────────[ M ]
                   │         ║
q_2: ──────────────X─────────[ M ]
Probabilities: |000>: 50.0%, |111>: 50.0%
💡 What Does This Demonstration Show?

The GHZ state represents genuine tripartite entanglement: all 3 qubits are entangled such that measuring any single qubit immediately collapses all 3 qubits simultaneously.

Course Learning Resource • Slide DeckLesson 311 Slides

Lesson 3: Quantum Measurement with a One-Qubit Circuit

Hadamard gate, quantum registers, simulation, and histogram measurement.

Author: Dr. Syed Muzamil Basha• FDP Approved Curriculum
Open in New Tab
Available Slide Decks:

📝 Learning Check

Test your understanding with these questions. Remember, this is for learning, not examination!

Question 1: What is the purpose of the Qiskit Transpiler?

Question 2: What is the first step in building a quantum circuit?

Question 3: What is the typical workflow for building and running a quantum circuit?

Question 4: Why must quantum circuits be designed considering coherence time?

Question 5: What is circuit transpilation in quantum computing?