Loops and Conditionals Cheat Sheet

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 2

LOOPS AND CONDITIONALS CHEAT SHEET

Loops
A for loop to execute the same code multiple for index in range(number):
times: code to repeat
- index is the loop control variable, which
takes on each value in the range, one at a
time. This follows the same naming
conventions as any other variable.
- range(number) provides all the numbers
from 0 up to, but not including, number

NOTE: Don’t forget the colon at the end.

An example demonstrating how we can apply gates qc = QuantumCircuit(26)


using a for loop. Here we create a quantum circuit
with 26 qubits, then apply an H gate to every single for index in range(26):
qubit (from 0 to 25). qc.h(index)

Conditionals (If Statements)


A conditional or if statement to perform different if condition:
actions depending on whether the condition Run if condition is True
else:
(comparison) is True or False.
Run if condition is False

NOTE: Don’t forget the colon at the end for both the if
and else.

An example demonstrating how we can apply gates qc = QuantumCircuit(2)


using a conditional. Here we create a quantum choice = “not”
circuit with 2 qubits and apply an X gate if the
variable choice stores the string “not” or an H gate if choice == “not”:
otherwise. Changing the value of the variable qc.x(0)
would change the circuit we create. else:
qc.h(0)
Comparisons
Greater than? >

Greater than or equal to? >=

Less than? <

Less than or equal to? <=

Equal to? ==

Not equal to? !=

You might also like