I have read about the global and nonlocal variable and I know they may solve the problem, but as I'm still naive at this I couldn't figure out how to implement them to solve the UnboundLocalError. Sorry for the long program I put here:
# initialization
import numpy as np
# import Qiskit
from qiskit import IBMQ, BasicAer
from qiskit.providers.ibmq import least_busy
from qiskit import QuantumCircuit, execute
from qiskit.tools.jupyter import *
#provider= IBMQ.load.account()
provider= IBMQ.load_account()
#import basic plot tools
from qiskit.visualization import plot_histogram
Here is the Dj function
def dj_oracle(case, n):
#We need to make a QuantumCircuit object to return
#This circuit has n+1 qubits: the size of the input,
#plus one output qubit
oracle_qc=QuantumCircuit(n+1)
#First, let's deal with the case in which oracle is balanced
if case == "balanced":
# We apply controlled-NOT gates for each qubit, using the
#output qubit as target
for qubit in range(n):
oracle_qc.cx(qubit, n)
# case in oracle is constant
if case == "constant":
# First decide what the fixed output of the oracle will be
# (either always 0 or always 1)
output = np.random.randint(2)
if output == 1:
oracle_qc.x(n)
oracle_gate = oracle_qc.to_gate()
oracle_gate.name ="Oracle"
return oracle_gate
and Here is the dj_algorithm
def dj_algorithm(n, case='random'):
dj_circuit=QuantumCircuit(n+1, n)
# Set up the input register:
for qubit in range(n):
dj_circuit.h(qubit)
#And set up the output qubit:
dj_circuit.x(n)
dj_circuit.h(n)
#Let's append the oracle gate to our circuit:
if case == 'random':
random = np.random.randint(2)
if random == 0:
case = 'constant'
else:
case = 'balanced'
oracle = dj_oracle(case, n)
dj_circuit.append(oracle, range(n+1))
# Finally, perform the H-gates again and measure:
for i in range(n):
dj_circuit.h(i)
dj_circuit.measure(i,i)
return dj_circuit
Now when I want to use the local simulator to get the results, I face the UnboundLocalError, Can anybody help me to solve it?
This is the error I get:
UnboundLocalError Traceback (most recent call last)
<ipython-input-112-f0c5e2ae7e9a> in <module>
2 backend = BasicAer.get_backend('qasm_simulator')
3 shots = 1024
----> 4 dj_circuit = dj_algorithm(n,'constant')
5 results = execute(dj_circuit, backend=backend, shots=shots).result()
6 answer = results.get_counts()
<ipython-input-89-6104e1173619> in dj_algorithm(n, case)
15 else:
16 case = 'balanced'
---> 17 oracle = dj_oracle(case, n)
18 dj_circuit.append(oracle, range(n+1))
19 # Finally, perform the H-gates again and measure:
<ipython-input-110-75bb51aa8b15> in dj_oracle(case, n)
22 output = np.random.randint(2)
23
---> 24 if output == 1:
25
26 oracle_qc.x(n)
UnboundLocalError: local variable 'output' referenced before assignment
UnboundLocalError
, what is the description follows after that? $\endgroup$ – KAJ226 Nov 4 '20 at 18:45