> ## Documentation Index
> Fetch the complete documentation index at: https://docs.classiq.io/llms.txt
> Use this file to discover all available pages before exploring further.

# Qmod Tutorial - Part I

> [card] [View on GitHub](https://github.com/Classiq/classiq-library/blob/main/tutorials/basic_tutorials/the_classiq_tutorial/Qmod_tutorial_part1.ipynb)
>
> Open this notebook in GitHub to run it yourself

Welcome to the Qmod tutorial! **Qmod** is Classiq's quantum programming language,
embedded in Python (Qmod also has standalone syntax which we will not cover here).

Across two notebooks you will build up the core toolkit for designing
quantum algorithms at a high level of abstraction, letting the Classiq synthesis engine
handle the gate-level implementation for you.

**Part I** (this notebook) covers the language foundations.

After a short warmup, six sections each pair a concept with a hands-on exercise:

1. Quantum Variables and Quantum Types
2. Output Parameters and State-Preparation Functions
3. Classical Parameters
4. Classical Control Flow
5. Quantum Assignment and Arithmetic
6. Control Statements

Each section has a short concept explanation followed by an exercise.

Complete the code where
marked with `# TODO`, then synthesize and run it. **All solutions are
collected at the end of the notebook** - try each exercise before peeking.

**Part II** then builds on these foundations with six more concepts - the statements and operators used to express real quantum algorithms.

> **Note:** If you are working in your own SDK environment, make sure Classiq is installed
> (`pip install -U classiq`) and that you have authenticated once by running `authenticate()`
> in a Python session. See the
> [registration and installation guide](https://docs.classiq.io/latest/getting-started/registration_installations.md).

```python theme={null}
# Run once per environment to authenticate:
# import classiq
# classiq.authenticate()

from classiq import *
from classiq.qmod.symbolic import pi
```

## Warmup

* Quantum Functions and `main`

The `@qfunc` decorator designates a
[quantum function](https://docs.classiq.io/qmod-reference/language-reference/functions.md) - a
function that applies operations to quantum objects.

The **entry point** of a quantum program, that is, the quantum function synthesized into an executable, must be named `main`.

The quantum parameters of `main` are designated with the `Output`-modifier, and they are measured when the program is executed.

Function `main` can call other quantum functions.

A typical SDK flow is:

* Compile the high-level model into a gate-level **quantum program** with `synthesize()`.
* Visualize the quantum program with `show()`.
* Execute the program and sample the state prepared in its output variables with `sample()`.

**Exercise:** *No coding required.* The cell below prepares and samples a **Bell state**, one of
the most fundamental entangled states, $\frac{1}{\sqrt{2}}(|00\rangle + |11\rangle)$.

Just run
it and observe the synthesis -> visualization -> execution flow.

```python theme={null}
@qfunc  # this decorator declares a quantum function
def create_bell_state(pair: QArray[QBit, 2]):
    H(pair[0])
    CX(pair[0], pair[1])


@qfunc  # 'main' is the entry point of the quantum program
def main(res: Output[QArray[QBit, 2]]):
    allocate(res)
    create_bell_state(res)


qprog = synthesize(main)  # compile to a gate-level quantum program
show(qprog)  # visualize in the Classiq IDE
df = sample(qprog)
display(df)
```

> **Expected result:** roughly 50% of the samples are the bit vector `00` and 50% are `11` -
> the two qubits are perfectly correlated.

##

1. Quantum Variables and Quantum Types

A quantum **variable** is a reference to a **quantum object** - the quantum state stored on one or more specific qubits.

Its
[type](https://docs.classiq.io/qmod-reference/language-reference/quantum-types.md) tells the
compiler how to interpret and operate on those qubits:

* `QBit` - a single qubit.
* `QNum` - a number, supporting arithmetic and comparisons.

You can specify its size, signedness,
and fractional digits (e.g. `QNum[3, SIGNED, 0]`).

* `QArray` - an indexable array (e.g. `my_qarr[i]`) of elements of any quantum type; `QArray[QBit]` is the
  most common.
* `QStruct` - a struct of named fields (e.g. `my_qstruct.f`); we'll return to structs later.

Size and length are optional - leave them unspecified (e.g. `QNum`, `QArray[QBit]`) and the
compiler infers them when the variable is initialized.

Function arguments are automatically **cast** between quantum types of the same size - e.g. between
`QArray[QBit]` and `QNum` - so the same function can operate on either.

**Exercise A:** Based on the Bell-state example above, complete `create_ghz_state` to prepare a
3-qubit **GHZ state** $\frac{1}{\sqrt{2}}(|000\rangle + |111\rangle)$, then synthesize, show, and
sample it.

```python theme={null}
@qfunc
def create_ghz_state(qubits: QArray[QBit, 3]):
    # TODO: entangle the three qubits into a GHZ state
    # Hint: one Hadamard, then a chain of CX gates
    pass


@qfunc
def main(res: Output[QArray[QBit, 3]]):
    allocate(res)
    create_ghz_state(res)


qprog = synthesize(main)
show(qprog)

df = sample(qprog)
display(df)
```

> **Expected result:** roughly 50% `000` and 50% `111`.

**Exercise B:** Reuse the *same* `create_ghz_state` from Exercise A, but this time call it on a
*signed* quantum number `x` (`QNum[3, SIGNED, 0]`) instead of a qubit array.

Synthesize and
sample it.

What values do you expect to measure?

> **Tip:** Thanks to automatic casting between `QArray[QBit]` and `QNum`, you don't need to change
> `create_ghz_state` at all. The bit string `111` is interpreted as $-1$ for a signed integer (in two's-complement representation, the MSB has weight $-2^{n-1}$, so `111` $= -4 + 2 + 1 = -1$).

```python theme={null}
@qfunc
def main(x: Output[QNum[3, SIGNED, 0]]):
    allocate(x)
    # TODO: call create_ghz_state on x (the same function from Exercise A)


qprog = synthesize(main)
df = sample(qprog)
display(df)
```

> **Expected result:** roughly 50% for the value `0` and 50% for the value `-1`.

##

2. Output Parameters and State-Preparation Functions

By default, a quantum parameter refers to an object passed *into* the function and back *out* to the caller - it is already initialized when entering the function.

Declaring a parameter `Output` makes it **output-only**: it starts uninitialized and must be initialized inside the function.

A variable is initialized by:

* allocating fresh qubits in the $|0\rangle$ state (using `allocate()`)
* assigning an object in a state specified as an expression (using `|=`)
* calling a state-preparation function (a function with an `Output` parameter)

See also [Quantum variables](https://docs.classiq.io/qmod-reference/language-reference/quantum-variables.md).

> **Note:** All of `main`'s parameters must be `Output` - as the entry point, there is nowhere they could have been initialized beforehand.

Classiq provides built-in [state-preparation functions](https://docs.classiq.io/qmod-reference/library-reference/core-library-functions/prepare_state_and_amplitudes/prepare_state_and_amplitudes.md).

Two closely related ones:

* `prepare_state(probabilities, bound, out)` - allocates a fresh object and prepares it in a state whose measurement distribution matches `probabilities` (**out-of-place**).
* `inplace_prepare_state(probabilities, bound, target)` - applies the same preparation to an **already-allocated** object `target` (**in-place**), assumed to be in the $|0\rangle$ state.

(In both cases, `bound` determines the maximum allowed error.)

**Exercise A:** Load the *same* distribution `dist` two ways, to contrast the two functions:

1. Use `prepare_state` to load `dist` into a **fresh** variable `a`.
2. Use `inplace_prepare_state` to load `dist` into an **already-allocated** variable `b`.

`dist` has 8 entries, so each variable holds 3 qubits.

```python theme={null}
dist = [0.3, 0.2, 0.05, 0.13, 0.15, 0.05, 0.1, 0.02]  # 8 entries, sums to 1


@qfunc
def main(a: Output[QArray[QBit, 3]], b: Output[QArray[QBit, 3]]):
    # TODO (out-of-place): load dist into the fresh variable a with prepare_state
    allocate(a)  # placeholder — replace this line with your prepare_state call

    # TODO (in-place): allocate b, then load dist into it with inplace_prepare_state
    allocate(b)  # placeholder — keep the allocate, then add inplace_prepare_state


qprog = synthesize(main)
show(qprog)

df = sample(qprog, num_shots=10000)
display(df)
```

> **Expected result:** The probability of measuring `000` on both `a` and `b` is the highest - $0.3 \times 0.3$, and the probability of measuring `111` on both should be the lowest - $0.02 \times 0.02$.

**Exercise B:** The cell below fails - the variable `q` is never initialized.

Run it to see the
error, then fix it such that `prep` is responsible for initializing `q`.

```python theme={null}
@qfunc
def prep(q: QBit):  # should be responsible for q's initialization
    H(q)


@qfunc
def main(q: Output[QBit]):
    prep(q)


try:
    qprog = synthesize(main)
except Exception as e:
    print(f"Synthesis error: {e}")
```

##

3. Classical Parameters

Qmod functions can take **classical** parameters, in addition to quantum parameters.

You already used them in Exercise A of Section 2 - the parameters of `prepare_state()`.

Classical parameters are declared with Qmod [classical types](https://docs.classiq.io/qmod-reference/language-reference/classical-types.md)

* `CInt`, `CReal`, `CArray`, etc.

Classical parameters can be used in Qmod expressions and statements.

The size of quantum variables (e.g. `my_qnum.size`) and the length of arrays (e.g. `my_qarr.len`) are also classical expressions in Qmod.

When `main` has a classical parameter, its value is left symbolic throughout the compilation process, and is only determined upon execution.

This is useful for hybrid quantum-classical algorithms.

> **Note:** Qmod classical types (`CInt`, `CReal`, etc.) remain symbolic through compilation. Parameters declared with plain Python types (`int`, `float`) also work, and can be used in arbitrary Python expressions. But they can't serve as execution parameters, and they might hurt compilation performance. See also [generative descriptions](https://docs.classiq.io/qmod-reference/language-reference/generative-descriptions.md).

**Exercise A:** Define the function `rotate` to rotate qubit `ind` of `qarr` about the X axis by `turns`, given as a fraction of the full $2\pi$ rotation. (Here the classical parameter `turns` is used *inside an expression*, not passed directly.)

```python theme={null}
@qfunc
def rotate(turns: CReal, ind: CInt, qarr: QArray[QBit]):
    # TODO: apply RX() to rotate qubit ind of qarr by turns
    #       i.e. by an angle of 2*pi*turns radians (a classical expression)
    pass


@qfunc
def main(qarr: Output[QArray[QBit]]):
    allocate(2, qarr)
    rotate(0.3, 0, qarr)
    rotate(0.2, 1, qarr)


qprog = synthesize(main)
show(qprog)
```

> **Expected result:** Note how the parameter `turns` under `rotate` remains symbolic in the quantum program visualization.

**Exercise B:** Rewrite function `main` from Exercise A such that it takes two execution parameters, `alpha` and `beta`, for the rotation of the two qubits, instead of hard-coding them inside `main`.

```python theme={null}
@qfunc
def main(alpha: CReal, beta: CReal, qarr: Output[QArray[QBit]]):
    allocate(2, qarr)
    # TODO: call 'rotate' with the two execution parameters on the two qubits


qprog = synthesize(main)
sample(qprog, parameters={"alpha": 0.3, "beta": 0.2})
```

##

4. Classical Control Flow

Much like other programming languages, Qmod supports [loops and conditional statements](https://docs.classiq.io/qmod-reference/language-reference/statements/classical-control-flow.md): `repeat`, `foreach`, and `if_`. To specify the body of the loop, or the branches of the conditional, you typically use lambda expressions. In `repeat` and `foreach`, the iteration variable is the lambda parameter. `power` is a unique form of a loop statement with no iteration variable, and stronger optimizations for some special cases.

For example, the following uses `repeat` to apply a Hadamard gate to each qubit in a qubit array (the **Hadamard transform**):

```python theme={null}
repeat(target.len, lambda i: H(target[i]))
```

Qmod also provides this as the built-in function `hadamard_transform`, which we'll use in later sections.

> **Note:** Python `for` and `if` statements can be used inside Qmod functions. But these Python statements cannot use Qmod (symbolic) variables. They generate a flat unrolled description, which can impact compilation performance.

**Exercise:** Rewrite `rotate` from Section 3 so that it takes an array of turn-fractions and rotates the *i*th qubit of `qarr` by the *i*th value (you can assume that the arrays are of the same length).

```python theme={null}
@qfunc
def rotate_layer(turns: CArray[CReal], qarr: QArray[QBit]):
    # TODO: rotate qubit i of qarr by turns[i] full turns (2*pi*turns[i] radians)
    pass


@qfunc
def main(qarr: Output[QArray[QBit]]):
    allocate(3, qarr)
    rotate_layer([0.1, 0.3, 0.5], qarr)


qprog = synthesize(main)
show(qprog)
```

##

5. Quantum Assignment and Arithmetic

Qmod lets you write ordinary [arithmetic expressions](https://docs.classiq.io/user-guide/modeling/quantum-numbers-arithmetics.md) over `QNum` variables; the compiler
synthesizes them into reversible quantum circuits automatically.

There are three flavors of
assignment:

* **out-of-place**: `res |= expr` allocates `res` and sets it to the result of `expr`.

Used
to initialize a fresh variable.

* **in-place-add**: `x += expr` adds `expr` into an already-initialized `x`.
* **in-place-xor**: `x ^= expr` XORs `expr` onto an already-initialized `x`.

When applied to variables in *superposition*, the arithmetic is carried out coherently over every basis
state.

**Exercise (out-of-place):** Put two 2-qubit unsigned integers `x` and `y` into uniform
superposition, then use `|=` to compute both their sum `total = x + y` and their product
`prod = x * y`.

Synthesize and sample.

```python theme={null}
@qfunc
def main(x: Output[QNum], y: Output[QNum], total: Output[QNum], prod: Output[QNum]):
    allocate(2, x)
    allocate(2, y)
    hadamard_transform(x)
    hadamard_transform(y)

    # TODO: assign the sum x + y to total, and the product x * y to prod
    total |= 0  # placeholder — replace with the sum
    prod |= 0  # placeholder — replace with the product


qprog = synthesize(main)
show(qprog)

df = sample(qprog)
display(df)
```

> **Expected result:** `x` and `y` are each uniform over 0-3; each row shows `total = x + y` (0-6) and `prod = x * y` (0-9) for that pair of values.

**Exercise (in-place):** Initialize `acc` to the fixed value `4`, then add a superposed `y` into it
*in place* with `+=`.

Notice how `acc` becomes correlated with `y`.

```python theme={null}
@qfunc
def main(y: Output[QNum], acc: Output[QNum]):
    allocate(2, y)
    hadamard_transform(y)
    acc |= 4  # fixed starting value; 4 = 0b100, so acc is inferred as 3-bit

    # TODO: add y into acc in place


qprog = synthesize(main)
show(qprog)

df = sample(qprog)
display(df)
```

> **Expected result:** `acc = 4 + y`, i.e. 4, 5, 6, and 7 - each paired with the `y` that produced it.

##

6. Control Statements

The [`control`](https://docs.classiq.io/qmod-reference/language-reference/statements/control) operator conditionally applies a quantum operation. In its basic form the condition
is that all control qubits are $|1\rangle$, but Qmod generalizes this: the condition can be *any
Boolean expression* over quantum numeric variables - comparisons (`==`, `<`, `>=`, ...) and
logical operators (`&`, `|`). It resembles a classical `if` statement, except the operation is
applied *in superposition* over the states that satisfy it.

For example, the following applies `H` to `q` only when the control qubit `flag` is $|1\rangle$:

```python theme={null}
control(flag, lambda: H(q))
```

> **Tip:** `control` also accepts an optional `else_block=` that applies when the condition is
> *False*. And the condition can involve real-valued `QNum`s too (e.g. `x < 0.5`), not just
> integers.

**Exercise:** Put a 3-qubit number `x` into uniform superposition, then flip the `target` qubit to
$|1\rangle$ *only* for the basis state where `x` equals `5`.

```python theme={null}
@qfunc
def main(x: Output[QNum], target: Output[QBit]):
    allocate(3, x)
    hadamard_transform(x)
    allocate(target)

    # TODO: flip target (X gate) only when x == 5


qprog = synthesize(main)
show(qprog)

df = sample(qprog)
display(df)
```

> **Expected result:** `x` is uniform over `0`-`7`; `target` is `1` only in the row where `x == 5`,
> and `0` everywhere else.

## Solutions

Try each exercise before checking the solution below.

#

## Solution 1

* Quantum Variables and Quantum Types

\*\*Exercise A

* GHZ on a qubit array\*\*

```python theme={null}
@qfunc
def create_ghz_state(qubits: QArray[QBit, 3]):
    H(qubits[0])
    CX(qubits[0], qubits[1])
    CX(qubits[1], qubits[2])


@qfunc
def main(res: Output[QArray[QBit, 3]]):
    allocate(res)
    create_ghz_state(res)


qprog = synthesize(main)
df = sample(qprog)
display(df)
```

\*\*Exercise B

* GHZ on a signed integer\*\*

```python theme={null}
@qfunc
def main(x: Output[QNum[3, SIGNED, 0]]):
    allocate(x)
    create_ghz_state(x)  # the very same function, now cast onto a QNum


qprog = synthesize(main)
df = sample(qprog)
display(df)
```

#

## Solution 2

* Output Parameters and State-Preparation Functions

**Exercise A - prepare\_state vs. inplace\_prepare\_state**

```python theme={null}
dist = [0.3, 0.2, 0.05, 0.13, 0.15, 0.05, 0.1, 0.02]  # 8 entries, sums to 1


@qfunc
def main(a: Output[QArray[QBit, 3]], b: Output[QArray[QBit, 3]]):
    # out-of-place: prepare_state allocates a itself
    prepare_state(probabilities=dist, bound=0.01, out=a)

    # in-place: b must already be allocated
    allocate(b)
    inplace_prepare_state(probabilities=dist, bound=0.01, target=b)


qprog = synthesize(main)
df = sample(qprog, num_shots=10000)
display(df)
```

**Exercise B - fixing the uninitialized variable**

```python theme={null}
# The fix: whoever initializes q must own it.

Either allocate q inside prep
# (make it an Output), or allocate it in main before calling prep.
@qfunc
def prep(q: Output[QBit]):
    allocate(q)
    H(q)


@qfunc
def main(q: Output[QBit]):
    prep(q)


qprog = synthesize(main)
```

#

## Solution 3

* Classical Parameters

**Exercise A - a classical expression in a rotation**

```python theme={null}
@qfunc
def rotate(turns: CReal, ind: CInt, qarr: QArray[QBit]):
    RX(2 * pi * turns, qarr[ind])


@qfunc
def main(qarr: Output[QArray[QBit]]):
    allocate(2, qarr)
    rotate(0.3, 0, qarr)
    rotate(0.2, 1, qarr)


qprog = synthesize(main)
```

**Exercise B - execution parameters**

```python theme={null}
@qfunc
def main(alpha: CReal, beta: CReal, qarr: Output[QArray[QBit]]):
    allocate(2, qarr)
    rotate(alpha, 0, qarr)
    rotate(beta, 1, qarr)


qprog = synthesize(main)
sample(qprog, parameters={"alpha": 0.3, "beta": 0.2})
```

#

## Solution 4

* Classical Control Flow

```python theme={null}
@qfunc
def rotate_layer(turns: CArray[CReal], qarr: QArray[QBit]):
    repeat(turns.len, lambda i: RX(2 * pi * turns[i], qarr[i]))


@qfunc
def main(qarr: Output[QArray[QBit]]):
    allocate(3, qarr)
    rotate_layer([0.1, 0.3, 0.5], qarr)


qprog = synthesize(main)
```

#

## Solution 5

* Quantum Assignment and Arithmetic

**Out-of-place assignment**

```python theme={null}
@qfunc
def main(x: Output[QNum], y: Output[QNum], total: Output[QNum], prod: Output[QNum]):
    allocate(2, x)
    allocate(2, y)
    hadamard_transform(x)
    hadamard_transform(y)
    total |= x + y
    prod |= x * y


qprog = synthesize(main)
df = sample(qprog)
display(df)
```

**In-place assignment**

```python theme={null}
@qfunc
def main(y: Output[QNum], acc: Output[QNum]):
    allocate(2, y)
    hadamard_transform(y)
    acc |= 4  # fixed starting value; 4 = 0b100, so acc is inferred as 3-bit
    acc += y


qprog = synthesize(main)
df = sample(qprog)
display(df)
```

#

## Solution 6

* Control Statements

```python theme={null}
@qfunc
def main(x: Output[QNum], target: Output[QBit]):
    allocate(3, x)
    hadamard_transform(x)
    allocate(target)
    control(x == 5, lambda: X(target))


qprog = synthesize(main)
df = sample(qprog)
display(df)
```


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.