# How to add control to gates in Cirq?

My question is very simple. I know there is a method to add a control to previously defined gates. I saw in the API of cirq that there is a command Controlled gate (here). I'm not understanding though how would this work. Suppose for example I want to add a control to an XPowGate from cirq. How would I write this in a program and how would I define the control qubit and the qubit over which I want to act?

You can use the controlled_by method on any Operation:

op = cirq.X(target_qubit).controlled_by(control_qubit)


You can also use controlled before specifying the target qubits:

op = cirq.X.controlled().on(control_qubit, target_qubit)


There are also built-in controlled operations such as cirq.CNOT, cirq.CZ, and cirq.CSWAP. The built-in operations are generally preferable because they have hand-tuned gate decompositions and simulation methods. The general controlled_by has to fall back to more general methods.

Note that the controlled versions of gates support things like raising to a power. The following three expressions produce equivalent operations:

(cirq.X(q)**0.5).controlled_by(c)

(cirq.X**0.5).on(q).controlled_by(c)

cirq.X(q).controlled_by(c)**0.5

• Thank you! if I have to a two-qubit gate and want to add a control, then I would have to write: controlled_x = cirq.ControlledGate(cirq.TwoQubitGate) return controlled_x.on(control_qubit, target_qubit1, target_qubit2) right?
– Pam
Feb 19 '19 at 6:31
• @Pam That's right. Feb 19 '19 at 10:12