Operadores
## Objetivos de Aprendizaje
- Dominar operadores aritméticos
- Entender operadores de comparación
- Aprender operadores lógicos y bit a bit
- Trabajar con operadores de asignación
## Operadores Aritméticos
### Operaciones Básicas
```python
a, b = 10, 3
print(a + b) # 13 (suma)
print(a - b) # 7 (resta)
print(a * b) # 30 (multiplicación)
print(a / b) # 3.333... (división - siempre float)
print(a // b) # 3 (división entera)
print(a % b) # 1 (módulo - residuo)
print(a ** b) # 1000 (exponenciación)
```
### Comportamiento de la División
```python
# Python 3: / siempre devuelve float
print(10 / 2) # 5.0
print(10 / 3) # 3.3333333333333335
# // para división entera (floor)
print(10 // 3) # 3
print(-10 // 3) # -4 (redondea hacia menos infinito)
```
### Módulo con Números Negativos
```python
print(10 % 3) # 1
print(-10 % 3) # 2 (resultado siempre positivo)
print(10 % -3) # -2
```
## Operadores de Comparación
### Comparaciones Básicas
```python
a, b = 5, 10
print(a == b) # False (igual)
print(a != b) # True (no igual)
print(a < b) # True (menor que)
print(a > b) # False (mayor que)
print(a <= b) # True (menor o igual)
print(a >= b) # False (mayor o igual)
```
### Comparaciones Encadenadas
```python
x = 5
print(1 < x < 10) # True
print(1 < x < 3) # False
print(x > 0 and x < 10) # Igual que arriba
```
### Comparación de Cadenas
```python
print("manzana" == "manzana") # True
print("manzana" == "Manzana") # False (sensible a mayúsculas)
print("manzana" < "banana") # True (alfabético)
print("a" < "A") # False (orden ASCII)
```
## Operadores Lógicos
### and, or, not
```python
x, y = True, False
print(x and y) # False
print(x or y) # True
print(not x) # False
print(not y) # True
```
### Valores de Verdad
```python
# and devuelve el primer valor falsy o el último valor
print(0 and 5) # 0
print(1 and 5) # 5
print(None and 0) # None
# or devuelve el primer valor truthy o el último valor
print(0 or 5) # 5
print(None or 0) # 0
print(1 or 5) # 1
# Evaluación de cortocircuito
x = 5
y = 0
resultado = y != 0 and x / y > 0 # ¡Sin división por cero!
```
### Booleano a Int
```python
print(True + True) # 2
print(False + 1) # 1
```
## Operadores Bit a Bit
### Operaciones Binarias
```python
a, b = 5, 2 # 101 y 010 en binario
print(a & b) # 0 (AND: 101 & 010 = 000)
print(a | b) # 7 (OR: 101 | 010 = 111)
print(a ^ b) # 7 (XOR: 101 ^ 010 = 111)
print(~a) # -6 (NOT: ~101 = ...010 = -110)
print(a << 1) # 10 (desplazamiento a la izquierda)
print(a >> 1) # 2 (desplazamiento a la derecha)
```
### Usos Comunes
```python
# Verificar si un bit está activo
banderas = 0b1010 # decimal 10
print(banderas & 0b1000 != 0) # True (8 está activo)
# Activar un bit
banderas = banderas | 0b0001 # Activar bit 0
# Limpiar un bit
banderas = banderas & ~0b0010 # Limpiar bit 1
# Alternar un bit
banderas = banderas ^ 0b0100 # Alternar bit 2
```
## Operadores de Asignación
### Asignación Simple
```python
x = 5
```
### Asignación Compuesta
```python
x = 5
x += 3 # x = 8
x -= 2 # x = 6
x *= 2 # x = 12
x /= 3 # x = 4.0
x //= 2 # x = 2.0
x %= 3 # x = 2.0
x **= 2 # x = 4.0
```
### Asignación Bit a Bit
```python
x = 5 # 0101 en binario
x &= 3 # 0101 & 0011 = 0001, entonces x = 1
x |= 3 # 0001 | 0011 = 0011, entonces x = 3
x ^= 3 # 0011 ^ 0011 = 0000, entonces x = 0
x <<= 2 # 0000 << 2 = 0000, entonces x = 0
x >>= 1 # 0000 >> 1 = 0000, entonces x = 0
```
## Operadores de Identidad
### is vs ==
```python
a = [1, 2, 3]
b = [1, 2, 3]
c = a
print(a == b) # True (valores iguales)
print(a is b) # False (diferentes objetos)
print(a is c) # True (mismo objeto)
# Valores singleton
x = None
print(x is None) # True
print(x is not None) # False
```
## Operadores de Membresía
### in, not in
```python
numeros = [1, 2, 3, 4, 5]
print(3 in numeros) # True
print(6 in numeros) # False
print(3 not in numeros) # False
# Cadenas
texto = "¡Hola, Mundo!"
print("¡Hola" in texto) # True
print("hola" in texto) # False (sensible a mayúsculas)
print("Mundo" not in texto) # False
```
## Precedencia de Operadores
### De Mayor a Menor
```python
# 1. Paréntesis
# 2. Exponenciación **
# 3. Unario +x, -x, ~x
# 4. *, /, //, %
# 5. Binario +, -
# 6. <<, >>
# 7. &
# 8. ^
# 9. |
# 10. Comparaciones (==, !=, <, >, <=, >=)
# 11. Boolean NOT: not
# 12. Boolean AND: and
# 13. Boolean OR: or
```
### Ejemplos
```python
print(2 + 3 * 4) # 14 (no 20)
print((2 + 3) * 4) # 20
print(2 ** 3 ** 2) # 512 (de derecha a izquierda: 2 ** 9)
print((2 ** 3) ** 2) # 64
print(not True or True) # True (not True = False, False or True = True)
print(not (True or True)) # False
```
## Resumen
- Aritméticos: `+`, `-`, `*`, `/`, `//`, `%`, `**`
- Comparación: `==`, `!=`, `<`, `>`, `<=`, `>=`
- Lógicos: `and`, `or`, `not`
- Bit a bit: `&`, `|`, `^`, `~`, `<<`, `>>`
- Asignación: `=`, `+=`, `-=`, etc.
- Identidad: `is`, `is not`
- Membresía: `in`, `not in`
- Precedencia: usa paréntesis para estar seguro
Comments
Comments powered by Giscus
To enable comments, add your Giscus embed code here.
Learn more about Giscus →