Search code examples
python-3.xqiskit

Qiskit NameError: name 'q0' is not defined


I wrote the following code to implement the Grover's algorithm using 3-qubits.

from qiskit import*
from qiskit.tools.visualization import*

list = [q0,q1,q2]
def ccz(qci,q0,q1,q2):
    qci.h(q2)
    qci.ccx(q0,q1,q2)
    qci.h(q2)
def grover(qci,q0,q1,q2):
    ccz(qci,q0,q1,q2)
    for i in range(list):
        qci.h(i)
        qci.x(i)
    ccz(qci,q0,q1,q2)
    for i in range(list):
        qci.x(i)
        qci.h(i)

bn = 3
q = QuantumRegister(bn)
c = ClassicalRegister(bn)
qc = QuantumCircuit(q,c)
for i in range(bn):
    qc.h(q[i])
grover(qc,q[0],q[1],q[2])
for i in range(bn):
    qc.measure(q[bn-i-1],c[i])
r = execute(qc,"local_qasm_simulator").result()
rc = r.get_counts()
print(rc)
plot_histogram(rc) 

But I got the error below. Why did my Jupyter notebook care only about "q0", not other elements in the list? How can I fix this?

NameError: name 'q0' is not defined

Solution

  • It gives you error about q0 because this is the first unknown variable that it encounters. Then it dies.

    There is improper flow in your program. You try to define the variable list:

    • you try to build it from the variables that are not defined yet,
    • you make it global and try to operate somehow in the functions, where you pass also pass variables as parameters,
    • this name list is not a good choice as it's a python built-in name.

    Try this one:

    from qiskit import *
    from qiskit.tools.visualization import *
    
    def ccz(qci, q0, q1, q2):
        qci.h(q2)
        qci.ccx(q0, q1, q2)
        qci.h(q2)
    
    
    def grover(qci, q0, q1, q2):
        ccz(qci, q0, q1, q2)
        for i in [q0, q1, q2]:
            qci.h(i)
            qci.x(i)
        ccz(qci, q0, q1, q2)
        for i in [q0, q1, q2]:
            qci.x(i)
            qci.h(i)
    
    bn = 3
    q = QuantumRegister(bn)
    c = ClassicalRegister(bn)
    qc = QuantumCircuit(q, c)
    for i in range(bn):
        qc.h(q[i])
    grover(qc, q[0], q[1], q[2])
    for i in range(bn):
        qc.measure(q[bn - i - 1], c[i])
    r = execute(qc, "local_qasm_simulator").result()
    rc = r.get_counts()
    print(rc)
    plot_histogram(rc)