I have tried to build a circuit for encryption. One function is:

def selector(qc, a, b, c):
    qc.measure(a, 0)
    if a == 1:
        qc.cswap(a, b, c)

When I run it in IBM quantum lab, only the else option appears to be working. Why is my a == 1 case never taking place?


2 Answers 2


Your code is always takes the else branch because you are branching on a == 1 where a is 0 (as you mentioned in your comment selector(fcircuit,0,1,2)).

I have the feeling that you are confusing circuit construction and execution time. In your code measure runs at circuit-execution-time, while your conditional is at circuit-construction-time.

Running a conditional at execution time requires dynamic circuits. In this case:

qc.measure(a, 0)                  # measures a into classical bit 0
with qc.if_test((0, 0)) as else_: # tests if classical bit 0 is 0
    qc.cswap(a, b, c)             # then branch
with else_:
    qc.id(b)                      # else branch
    qc.id(c)                      #

This condition (if_test) is not a Python branching, but a conditional that will run as the circuit is being executed.

  • $\begingroup$ thank you. need to understand more on it. $\endgroup$
    – Arpita
    Apr 19 at 13:43

When you say only the else is working, I assume you mean the cswap is never taking place. In your code, you compare a to 1, while a is a qubit identifier. What you need to check is the classical register bit to which the measurement has been saved.

qc.measure(a, 0) essentially means "measure qubit a and save the result to classical bit 0".

When you initialized your qc, you have either specified your classical register (in which case you can check its value under index 0 after the measurement) or you can use qc.clbits to see the classical bits of the circuit (see docs.)

Your code then becomes something like if qc.clbits[0] == 1

  • $\begingroup$ Thanks for your answer. I tried this. But the circuit returns the same. def selector(qc,a,b,c): qc.measure(a,0) if qc.clbits[0] == 1: qc.swap(b,c) else: qc.id(b) qc.id(c) $\endgroup$
    – Arpita
    Apr 14 at 7:22
  • $\begingroup$ My main circuit like : qreg_q = QuantumRegister(3, 'q') creg_c = ClassicalRegister(3, 'c') fcircuit = QuantumCircuit(qreg_q, creg_c) fcircuit.x(qreg_q[2]) fcircuit.x(qreg_q[0]) #fcircuit.x(qreg_q[0]) for i in range(3): fcircuit.barrier(i) selector(fcircuit,0,1,2) for i in range(3): fcircuit.measure(i,i) fcircuit.draw() $\endgroup$
    – Arpita
    Apr 14 at 7:24
  • $\begingroup$ Could you paste your code into the original question and we can try and sort it out? $\endgroup$
    – 3yakuya
    Apr 14 at 16:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.