# Operators, conditionals and loops

> Arithmetic and logic operators, the ternary, if and switch as expressions, and for and while loops with their limits.

## Operators

| Kind | Operators |
| --- | --- |
| Arithmetic | `+ - * / %` |
| Comparison | `== != > < >= <=` |
| Logic | `and`, `or`, `not` |
| Ternary | `cond ? a : b` |
| History | `x[n]` |
| Assignment | `=` declares, `:=` reassigns, `+= -= *= /=` update |

Use `:=` to change a variable after declaring it; `=` a second time declares a new one and is an error in the same scope.

## if and switch return values

Both can be used as expressions: the last line of the branch is the value.

```pine
//@version=6
indicator("Trend state")
fast = ta.ema(close, 12)
slow = ta.ema(close, 26)
state = if fast > slow and close > fast
    2
else if fast > slow
    1
else
    -1
plot(state, "State", style = plot.style_stepline, color = state > 0 ? color.teal : color.red)
```

`switch` picks the first matching case; a case with no expression is the default:

```pine
kind = input.string("EMA", options = ["SMA", "EMA"])
avg = switch kind
    "SMA" => ta.sma(close, 20)
    => ta.ema(close, 20)
```

## Loops

`for i = 0 to n` counts (inclusive), with an optional `by` step. `for x in array` walks an array. `while cond` repeats. `break` and `continue` work as you expect.

```pine
//@version=6
indicator("Up closes in the last 20 bars")
count = 0
for i = 0 to 19
    if close[i] > close[i + 1]
        count += 1
plot(count, "Up closes", color = color.teal)
```

> [!TIP]
> Most loops over history have a built-in that is faster and clearer: this one is `math.sum(close > close[1] ? 1 : 0, 20)`. Reach for a loop when no built-in fits.

## Loop limits

The engine stops a loop that runs past its iteration ceiling with "Loop exceeded maximum iterations", and a whole run must finish in 8 seconds. Bound every loop by a length, never by "all history". See [Limits](/docs/limits).
