# Code your first quantum circuit¶

Learn to code your first quantum circuit in Quantum Lab, without downloading anything to your computer. While you can benefit from having some familiarity with Python and linear algebra, you can get a sense of the big picture without those prerequisites.

## Overview¶

To code any quantum circuit in Quantum Lab, you follow three high-level steps:

**Build**: Design a quantum circuit that represents the problem you are considering.**Execute**: Run circuits on different backends, either systems or simulators.**Analyze**: Calculate summary statistics and visualize the results of your circuit jobs.

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

## Run code in Quantum Lab¶

### 1. Sign in¶

Go to IBM Quantum Experience. Click the
**Sign in** button in the upper right corner, then sign in or create an IBMid account.

### 2. Open Quantum Lab¶

Open Quantum Lab by clicking on the **Quantum Lab** icon in the left navigation
bar.

Click on **New Notebook +**. The first cell in your new notebook imports
Qiskit into your Jupyter Notebook environment.

### 3. Enter code into a notebook¶

Copy **Code Snippet 1** (below) and paste it in an empty code block cell in
your new notebook, then click the **Run** button. (You can also run the cell by holding the
**Shift** key and then pressing the **Enter/Return** key on your keyboard.)

**Code Snippet 1**

```
# Build
#------
# Create a Quantum Circuit acting on the q register
circuit = QuantumCircuit(2, 2)
# Add a H gate on qubit 0
circuit.h(0)
# Add a CX (CNOT) gate on control qubit 0 and target qubit 1
circuit.cx(0, 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
circuit.draw()
# END
```

```
Total count for 00 and 11 are: {'00': 471, '11': 529}
```

┌───┐ ┌─┐ q_0: ┤ H ├──■──┤M├─── └───┘┌─┴─┐└╥┘┌─┐ q_1: ─────┤ X ├─╫─┤M├ └───┘ ║ └╥┘ c: 2/═══════════╩══╩═ 0 1

### 4. Plot a histogram¶

To see a visualization of the results, copy and paste **Code Snippet 2**
(below) into the next empty cell in your notebook, and click the **Run** button. This visualization
is from a single-shot statevector simulator.

**Code Snippet 2**

```
# Analyze
#--------
# Plot a histogram
plot_histogram(counts)
```

## 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

Execute

Analyze

### 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
notebook in Quantum Lab, so they do not 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 qiskit.tools.jupyter 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)
circuit.cx(0, 1)
circuit.measure([0,1], [0,1])
```

The code above applies the following gates:

`QuantumCircuit.h(0)`

: A Hadamard gate on qubit`0`

, which puts it into a superposition state`QuantumCircuit.cx(0, 1)`

: A controlled-NOT operation () 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*n*th qubit’s measurement result will be stored in the*n*th classical bit.

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

In this state, there is a 50% chance of finding both qubits to have the
value `0`

and a 50% chance of finding both qubits to have the value `1`

.

### 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': 485, '11': 515}
```

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.

```
circuit.draw()
```

┌───┐ ┌─┐ q_0: ┤ H ├──■──┤M├─── └───┘┌─┴─┐└╥┘┌─┐ q_1: ─────┤ X ├─╫─┤M├ └───┘ ║ └╥┘ c: 2/═══════════╩══╩═ 0 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.

```
plot_histogram(counts)
```

The probabilities (relative frequencies) of observing the and 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 Quantum Lab landing page and create your own notebooks with cloud-based access to Qiskit, or continue your quantum journey with the Qiskit textbook, Learn Quantum Computation with Qiskit.