# 4.5 Logical operators

> `And`, `Or` and `Not` combine boolean answers: `And` needs both to be true, `Or` is happy with one and `Not` turns the answer around.

Web page: https://pseudolearn.app/en/spec/expresiones/logicos

> **In one sentence**
>
> `And`, `Or` and `Not` combine boolean answers: `And` needs both to be true, `Or` is happy with one and `Not` turns the answer around.

## 4.5.1 How it works

The three operators only accept `Boolean` values and return a `Boolean`.

| `a` | `b` | `a And b` | `a Or b` | `Not a` |
| --- | --- | --- | --- | --- |
| `True` | `True` | `True` | `True` | `False` |
| `True` | `False` | `False` | `True` | `False` |
| `False` | `True` | `False` | `True` | `True` |
| `False` | `False` | `False` | `False` | `True` |

### Program: Combining conditions

```pseudolearn
Algorithm Logica
  Define edad As Integer <- 15;
  Define socio As Boolean <- False;
  Write edad >= 12 And edad < 18, " ", Not socio, " ", edad < 12 Or socio;
EndAlgorithm
```

**Output**

```text
true true false
```

*The program finishes normally.*

## 4.5.2 Short circuit

`And` and `Or` evaluate the left part first. If that is enough to know the answer, **the right part is not computed**:

- `False And …` is always `False`.
- `True Or …` is always `True`.

**Figure 4.5-1: Short circuit**

At the top, False And a crossed-out division by zero: the result is False without computing the right side. Below, True Or the same division: the result is True.

With `And`, a false left side decides without looking at the right. With `Or`, a true left side does.

### Program: The right side that is never computed

```pseudolearn
Algorithm Cortocircuito
  Write True Or 1 Div 0 = 0, " ", False And 1 Div 0 = 0;
EndAlgorithm
```

**Output**

```text
true false
```

*The program finishes normally.*

The division by zero is there, but it never runs, so it does not stop the program. The short circuit suppresses the effects and failures of the right side; what it does not suppress is type checking: the right side must be a valid `Boolean` even when it is not computed.

> **Limit**
>
> - `1 And True` is rejected before running: numbers are not boolean answers.
> - `Not` binds tighter than comparisons: `Not 1 = 2` tries to negate the 1. Write `Not (1 = 2)`.

**In short**
- `And` needs both true; `Or`, at least one; `Not` inverts.
- They only accept `Boolean`.
- The right side of `And` and `Or` is only computed when needed.

**See also**
- [4.4 Comparison](https://pseudolearn.app/en/spec/expresiones/comparacion.md)
- [4.7 Precedence and associativity](https://pseudolearn.app/en/spec/expresiones/precedencia.md)
- [6.1 The If decision](https://pseudolearn.app/en/spec/control/si.md)
