Code your first quantum circuit

Learn to code your first quantum circuit without downloading anything to your computer, by using Qiskit Notebooks embedded within IBM Quantum Experience. While you can benefit from having some familiarity with Python and quantum computing, you can get a sense of the big picture without those prerequisites.


To code any quantum circuit with Qiskit, you follow three high-level steps:

  • Build: Design a quantum circuit that represents the problem you are considering.

  • Execute: Run experiments on different backends, either systems or simulators.

  • Analyze: Calculate summary statistics and visualize the results of experiments.

The following instructions guide you through building a circuit with example code in a Qiskit Notebook, executing your program, and analyzing the results. You will then learn in greater detail how each component of the program functions.

Run code in a Qiskit Notebook

Sign in to IBM Quantum Experience

  1. Go to IBM Quantum Experience.

  2. Sign in or Create an IBMid account.

page.

Open Qiskit Notebooks

  1. To open Qiskit Notebooks, select Qiskit Notebooks in the navigation bar.

    Left-hand navigation button for Qiskit Notebooks.
  2. Click on New Notebook +. The first cell in your new notebook imports Qiskit into your Jupyter Notebook environment.

    New Qiskit Notebook button.

Enter code into a notebook

  1. Copy Code Snippet 1 (below) and paste it in an empty code block cell in your new Qiskit Notebook.

  2. Click the Run button.

Code Snippet 1

# Build

# Create a Quantum Circuit acting on the q register
circuit = QuantumCircuit(2, 2)

# Add a H gate on qubit 0

# Add a CX (CNOT) gate on control qubit 0 and target qubit 1, 1)

# Map the quantum measurement to the classical bits
circuit.measure([0,1], [0,1])

# Execute

# Use Aer's qasm_simulator
simulator = Aer.get_backend('qasm_simulator')

# Execute the circuit on the qasm simulator
job = execute(circuit, simulator, shots=1000)

# Grab results from the job
result = job.result()

# Return counts
counts = result.get_counts(circuit)
print("\nTotal count for 00 and 11 are:",counts)

# Analyze

# Draw the circuit

Total count for 00 and 11 are: {'00': 524, '11': 476}
     ┌───┐     ┌─┐   
q_0: ┤ H ├──■──┤M├───
q_1: ─────┤ X ├─╫─┤M├
          └───┘ ║ └╥┘
c_0: ═══════════╩══╬═
c_1: ══════════════╩═

Plot a histogram

  1. To see a visualization of the results, copy and paste Code Snippet 2 (below) into the next empty cell in your notebook.

  2. Run the cell by holding the Shift key and then pressing the Enter/Return key on your keyboard.

Code Snippet 2

# Analyze

# Plot a histogram

Explanation: components of the program

The program contains six actions. The comments above each line of code indicate which of the six actions it is performing. Explore the details of each in the following sections.

  • Build

  1. Import packages

  2. Initialize variables

  3. Add gates

  • Execute

  1. Simulate the experiment

  • Analyze

  1. Visualize the circuit

  2. Visualize the results

Import packages

The import lines import the basic elements (packages and functions) needed for your program. The following imports are the default imports for any new Qiskit Notebook in IBM Quantum Experience, so they do no appear in the code snippet.

%matplotlib inline
# Importing standard Qiskit libraries and configuring account
from qiskit import QuantumCircuit, execute, Aer, IBMQ
from qiskit.compiler import transpile, assemble
from import *
from qiskit.visualization import *
# Loading your IBM Q account(s)
provider = IBMQ.load_account()

The imports used in the rest of the code example are

  • QuantumCircuit: Holds all your quantum operations; the instructions for the quantum system

  • execute: Runs your circuit

  • Aer: Handles simulator backends

  • qiskit.visualization: Enables data visualization, such as plot_histogram

Initialize variables

In the next line of code, you initialize two qubits in the zero state, and two classical bits in the zero state, in the quantum circuit called circuit.

circuit = QuantumCircuit(2, 2)

Add gates

The next three lines of code, beginning with circuit., add gates that manipulate the qubits in your circuit.

circuit.h(0), 1)
circuit.measure([0,1], [0,1])

The code above applies the following gates:

  • QuantumCircuit.h(0): A Hadamard gate H on qubit 0, which puts it into a superposition state

  •, 1): A controlled-NOT operation ( C_{X} ) on control qubit 0 and target qubit 1, putting the qubits in an entangled state

  • QuantumCircuit.measure([0,1], [0,1]): The first argument indexes the qubits, the second argument indexes the classical bits. The nth qubit’s measurement result will be stored in the nth classical bit.

This particular trio of gates added one-by-one to the circuit forms the Bell state,

|\psi\rangle = \left(|00\rangle+|11\rangle\right)/\sqrt{2}.

In this state, there is a 50 percent chance of finding both qubits to have the value zero and a 50 percent chance of finding both qubits to have the value one.

Simulate the experiment

The next line of code calls a specific simulator framework – in this case, it calls Qiskit Aer, which is a high-performance simulator that provides several backends to achieve different simulation goals.

In this program, you use the qasm_simulator. Each run of this circuit will yield either the bit string '00' or '11'.

simulator = Aer.get_backend('qasm_simulator')
job = execute(circuit, simulator, shots=1000)
result = job.result()
counts = result.get_counts(circuit)
print("\nTotal count for 00 and 11 are:",counts)

Total count for 00 and 11 are: {'00': 498, '11': 502}

The program specifies the number of times to run the circuit in the shots argument of the execute method (job = execute(circuit, simulator, shots=1000)). The number of shots of the simulation is set to 1000 (the default is 1024).

Once you have a result object, you can access the counts via the method get_counts(circuit). This gives you the aggregate outcomes of your experiment.

As expected, the output bit string is '00' approximately 50 percent of the time. This simulator does not model noise. Any deviation from 50 percent is due to the small sample size.

Visualize the circuit

QuantumCircuit.draw() (called by circuit.draw() in the code) displays your circuit in one of the various styles used in textbooks and research articles.

     ┌───┐     ┌─┐   
q_0: ┤ H ├──■──┤M├───
q_1: ─────┤ X ├─╫─┤M├
          └───┘ ║ └╥┘
c_0: ═══════════╩══╬═
c_1: ══════════════╩═

In this circuit, the qubits are ordered with qubit zero at the top and qubit one below it. The circuit is read from left to right, representing the passage of time.

Visualize the results

Qiskit provides many visualizations, including the function plot_histogram, to view your results.


The probabilities (relative frequencies) of observing the |00\rangle and |11\rangle states are computed by taking the respective counts and dividing by the total number of shots.

Next steps

Now that you have learned the basics, return to the Qiskit Notebooks landing page and create your own notebooks with cloud-based access to Qiskit, or continue your quantum journey with these resources.


Version Information

Qiskit SoftwareVersion
IBM Q Provider0.7.2
System information
Python3.7.6 (default, Feb 26 2020, 15:34:58) [GCC 8.3.0]
Memory (Gb)29.93264389038086
Fri Jun 26 10:06:06 2020 UTC

This code is a part of Qiskit

© Copyright IBM 2017, 2020.

This code is licensed under the Apache License, Version 2.0. You may
obtain a copy of this license in the LICENSE.txt file in the root directory
of this source tree or at

Any modifications or derivative works of this code must retain this
copyright notice, and modified files need to carry a notice indicating
that they have been altered from the originals.