# Classical Control Flow

Loops and conditionals on classical expressions are useful means to describe reusable building blocks. Qmod has two basic forms - the repeat statement and the if statement.

## Classical Repeat

### Syntax

repeat ( iteration_variable : count ) { iteration-statements }

def repeat(count: CInt, iteration: QCallable[CInt]) -> None:
pass


### Semantics

• Invoke the iteration block count times, binding the index variable to the respective iteration number - 0, 1,... count-1.
• Inside the statement block, use of quantum variables declared outside it is restricted to contexts where the variable is initialized and remains initialized (see Quantum Variables)

### Example

The following example defines a useful function - applying the Hadamard function across all qubits in a qubit array - using repeat. Note that a similar function is available in the Classiq open-library.

qfunc my_hadamard_transform(qba: qbit[]) {
repeat (index: qba.len) {
H(qba[index]);
}
}

from classiq import H, QArray, QBit, qfunc, repeat

@qfunc
repeat(
count=qba.len,
iteration=lambda index: H(qba[index]),
)


## Classical If

### Syntax

if ( condition ) { then-statements } else { else-statements }

def if_(condition: CBool, then: QCallable, else_: Optional[QCallable] = None) -> None:
pass


Note that identifiers in Qmod that happen to conflict with Python keywords have _ suffix. This is the case with if_ and else_ in the second function.

### Semantics

• Invoke the then block if condition evaluates to true and otherwise invoke the else block
• Inside the statement block, use of quantum variables declared outside it is restricted to contexts where the variable is initialized and remains initialized (see Quantum Variables)

### Example

qfunc my_conditional_gate(cond: bool, qb: qbit) {
if (cond) {
X(qb);
} else {
Y(qb);
}
}

from classiq import CBool, X, Y, QBit, qfunc, if_

@qfunc
def my_conditional_gate(cond: CBool, qb: QBit):
if_(
condition=cond,
then=lambda _: X(qb),
else_=lambda _: Y(qb),
)