class: center, middle, inverse, title-slide .title[ # Condicionales ] .subtitle[ ## MAD-UdelaR ] .author[ ### Daniel Miles Touya ] .date[ ### 2025-06-18 ] --- <style> .scroll-output { max-height: 300px; overflow-y: auto; background: #f9f9f9; border: 1px solid #ccc; padding: 10px; font-family: monospace; font-size: 70%; white-space: pre-wrap; } </style> # Condicionales Los <b style="color:#6082B6">condicionales</b> definen el flujo de un programa: .pull-left[ <img src="conditional1.png" style="height: 450px; width: 250px; padding: 0;"> ] .pull-right[ ````python x = int(input("What's x? ")) y = int(input("What's y? ")) if x < y: print("x is less than y") if x > y: print("x is greater than y") if x == y: print("x is equal to y") ```` ] --- # Condicionales > ¿Qué es una expresión booleana? >> Es simplemente una <b style = "color:green">pregunta que puede responderse con `True` o `False`</b>. >> Esto es útil porque el programa puede **tomar decisiones** fácilmente con solo dos posibles resultados. ```python x = 1 y = 2 if x < y: print("x es menor que y") ``` --- # Condicionales: Booleanos y Operadores Booleanos > ¿Qué es un type `bool` en Python? * Un <b style="color:#6082B6">booleano</b> representa un valor lógico: **Verdadero** o **Falso**. * En Python: * `True` → verdadero * `False` → falso ```python es_mayor = True tiene_licencia = False print(es_mayor,tiene_licencia) type(es_mayor),type(tiene_licencia) ``` -- >A menudo son el **resultado de una comparación**: ```python edad = 18 es_mayor = edad >= 18 print(es_mayor) # True ``` --- # Booleans: operadores **Operadores** logicos que dan resultados booleanos: | Operador | Significado | Ejemplo | Resultado | | -------- | ------------------------ | -------- | --------- | | `>` | Mayor que | `5 > 3` | `True` | | `<` | Menor que | `2 < 1` | `False` | | `>=` | Mayor o igual que | `5 >= 5` | `True` | | `<=` | Menor o igual que | `3 <= 2` | `False` | | `==` | Igual a | `4 == 4` | `True` | | `!=` | Distinto de (no igual a) | `4 != 5` | `True` | --- # Sintaxis de condicionales en Python ```python if x < y: print("x es menor que y") ``` Reglas importantes: * Se usa `:` al final del `if`. * La línea siguiente debe tener **indentación** (4 espacios o 1 tab). * La `indetation` define qué instrucciones se ejecutan si la condición es verdadera. --- # Conditional con varias condiciones con `if` .pull-left[ ```python x = int(input("x: ")) y = int(input("y: ")) if x < y: print("x es menor que y") if x > y: print("x es mayor que y") if x == y: print("x es igual a y") ``` ] .pull-right[ Flujo: de múltiples `if` ``` start ↓ ¿x < y? → sí → "x es menor" ↓ no ¿x > y? → sí → "x es mayor" ↓ no ¿x == y? → sí → "x es igual" ↓ stop ``` ] -- > Se evalúan **las 3 condiciones** aunque ya sepamos la respuesta con la primera. >> Enlentece el scirpt --- # `elif` .pull-left[ <img src="conditional2.png" style="height: 450px; width: 350px; padding: 0;"> ] .pull-right[ Mejora con `elif` ```python if x < y: print("x es menor que y") elif x > y: print("x es mayor que y") elif x == y: print("x es igual a y") ``` ] > Solo se evalúan las condiciones necesarias. --- # Mejor aún: usar `else` .pull-left[ <img src="conditional3.png" style="height: 450px; width: 350px; padding: 0;"> ] .pull-right[ ```python if x < y: print("x es menor que y") elif x > y: print("x es mayor que y") else: print("x es igual a y") ``` ] > Ya no hace falta verificar si `x == y`: >> Si no es menor ni mayor, **¡debe ser igual!!!!** --- # Conditionals: operadores booleanos | Operador | Nombre | Uso | | -------- | --------------- | --------------------------- | | `or` | O lógico | `True` si al menos una | | `and` | Y lógico | `True` si ambas condiciones | | `not` | Negación lógica | Invierte el valor | -- > `Or` .pull-left[ Hemos escrito ```python if x < y: print("x es menor que y") elif x > y: print("x es mayor que y") else: print("x es igual a y") ``` ] .pull-right[ Pero, con `or` ```python if x < y or x > y: print("x no es igual a y") else: print("x es igual a y") ``` ] -- > A veces queremos hacer una pregunta más general: **¿x es distinto de y?** --- # Operadores Booleanos .pull-left[ Observar que pudiesemos haber escrito ```python if x ! = y: print("x no es igual a y") else: print("x es igual a y") ``` ] .pull-right[ Alternativa ```python if x == y: print("x es igual a y") else: print("x no es igual a y") ``` ] --- # Conditionals: operadores booleanos >and A veces queremos verificar **dos condiciones a la vez**. .pull-left[ ```python if score >= 90 and score <= 100: print("A") ``` ] .pull-right[ ```python if 90 <= score <= 100: print("A") ``` ] -- Solo se imprime `"A"` si ambas condiciones son **verdaderas**: * La nota es **mayor o igual que 90** * Y **menor o igual que 100** --- # Conditionals: operadores booleanos .pull-left[ Imaginemos un esquema de notas: | Rango | Nota | | ------ | ---- | | 90–100 | A | | 80–89 | B | | 70–79 | C | | 60–69 | D | | < 60 | F | ] .pull-right[ ```python score = int(input("Score: ")) if score >= 90 and score <= 100: print("A") elif score >= 80 and score < 90: print("B") elif score >= 70 and score < 80: print("C") elif score >= 60 and score < 70: print("D") else: print("F") ``` ] -- <br> .pull-left[ >Funciona, pero se puede simplificar... ] --- # Conditionals: operadores booleanos .pull-left[ Imaginemos un esquema de notas: | Rango | Nota | | ------ | ---- | | 90–100 | A | | 80–89 | B | | 70–79 | C | | 60–69 | D | | < 60 | F | ] .pull-right[ ```python if score >= 90: print("A") elif score >= 80: print("B") elif score >= 70: print("C") elif score >= 60: print("D") else: print("F") ``` ] --- # `match`: una forma clara de manejar múltiples opciones <b style="color:brown">A partir de Python 3.10</b> `match` se usa para reemplazar largas cadenas de `if`/`elif`. Es similar a `switch` en otros lenguajes. -- >Ejemplo: queremos imprimir el idioma según el país ingresado: .pull-left[ ```python pais = input("País: ") match pais: case "España": print("Idioma: Español") case "Francia": print("Idioma: Francés") case "Alemania": print("Idioma: Alemán") case _: print("Idioma desconocido") ``` ] .pull-right[ Resultado <table> <thead> <tr> <th>Entrada</th> <th>Salida</th> </tr> </thead> <tbody> <tr> <td><code>España</code></td> <td><code>Idioma: Español</code></td> </tr> <tr> <td><code>Francia</code></td> <td><code>Idioma: Francés</code></td> </tr> <tr> <td><code>Italia</code></td> <td><code>Idioma desconocido</code></td> </tr> </tbody> </table> ] --- # `match` >Agrupando varios casos con `|` ```python match pais: case "España" | "México" | "Argentina": print("Idioma: Español") case "Francia": print("Idioma: Francés") case "Alemania" | "Austria": print("Idioma: Alemán") case _: print("Idioma desconocido") ``` * El símbolo `_` significa: "cualquier otro caso" (como `else`). * Es sensible a **mayúsculas y minúsculas**. --- # Conditionals `not` Expresión <b style="color:brown">not</b>: ```python not <expresión_booleana> ``` * <b style= "color:green">Invierte el valor de verdad de una expresión.</b> * Si algo es `True`, `not` lo convierte en `False`. * Si algo es `False`, `not` lo convierte en `True`. -- .pull-left[ ```python x = True print(not x) # False ``` ] .pull-right[ ```python y = False print(not y) # True ``` ] -- .pull-left[ Pensar el resultado ```python edad = 15 if not (edad >= 18): print("No puedes entrar") ``` ] --- # Conditionals `not` En Python, los siguientes valores se consideran "falsos": * `0` * `""` (cadena vacía) * `[]`, `{}`, `()` (listas, diccionarios o tuplas vacías) * `None` .pull-left[ ```python bool(0) bool("") # Probar dejando un espacio bool(" ") bool(None) ``` ] -- .pull-right[ ```python nombre = "" if not nombre: print("Debes ingresar un nombre") ``` ] -- .pull-left[ ```python activo = False if not activo: print("El usuario está inactivo") ``` ] -- .pull-right[ ```python if not mensaje.strip(): print("Mensaje vacío") ``` ] --- # Conditionals `not` Pero a veces `not` es más útil cuando la condición es más compleja: ```python if not (usuario_activo and tiene_permisos): print("Acceso denegado") ``` -- Tabla de verdad de `not (usuario_activo and tiene_permisos)` | `usuario_activo` | `tiene_permisos` | `usuario_activo and tiene_permisos` | `not (...)` | ¿Se imprime `"Acceso denegado"`? | | ---------------- | ---------------- | ----------------------------------- | ----------- | -------------------------------- | | False | False | False | True | ✅ Sí | | False | True | False | True | ✅ Sí | | True | False | False | True | ✅ Sí | | True | True | True | False | ❌ No | --- # Casos mas interesantes ````python import pandas as pd df = pd.DataFrame({ 'nombre': ['Ana', 'Luis', ''], 'edad': [25, 30, None] }) # Verificar si hay alguna columna sin datos válidos if not df.dropna().shape[0] == df.shape[0]: print(" Hay filas con datos faltantes o vacíos.") else: print("Todos los datos están completos.") ```` --- # Casos mas interesantes ````python import pandas as pd df = pd.DataFrame({ 'producto': ['pan', 'leche', 'queso'], 'precio': [1.2, 0.9, 3.5] }) # Buscar productos con precio > 10 resultado = df[df['precio'] > 10] if not len(resultado): print("🔍 No hay productos con precio mayor a 10.") else: print("Productos caros encontrados:") print(resultado) ```` --- # Casos mas interesantes ````python import pandas as pd df = pd.DataFrame({ 'nombre': ['Ana', 'Luis'], 'ventas': [1200, 950] }) # Verificar si la columna 'descuento' no existe if not 'descuento' in df.columns: print("La columna 'descuento' no existe en el DataFrame.") else: print("Columna encontrada.") ```` --- # `if` de una sola línea (simple) ```python if x > 0: print("positivo") ``` Ejecuta si se cumple la condición. -- ```python resultado = "mayor" if edad >= 18 else "menor" ``` > Sintaxis: ```python <valor_si_true> if <condición> else <valor_si_false> ``` --- # `if` en una sola linea <table style="font-size: 70%; border-collapse: collapse; width: 100%;"> <thead> <tr> <th style="border: 1px solid #ccc; padding: 4px;">Regla</th> <th style="border: 1px solid #ccc; padding: 4px;">Ejemplo en una línea</th> <th style="border: 1px solid #ccc; padding: 4px;">Versión recomendada</th> <th style="border: 1px solid #ccc; padding: 4px;">¿Usar una línea?</th> </tr> </thead> <tbody> <tr> <td style="border: 1px solid #ccc; padding: 4px;">Una sola acción simple</td> <td style="border: 1px solid #ccc; padding: 4px;"><code>if x > 0: print("positivo")</code></td> <td style="border: 1px solid #ccc; padding: 4px;"><code>if x > 0:<br> print("positivo")</code></td> <td style="border: 1px solid #ccc; padding: 4px;">✅ Sí</td> </tr> <tr> <td style="border: 1px solid #ccc; padding: 4px;">Múltiples acciones</td> <td style="border: 1px solid #ccc; padding: 4px;"><code>if x > 0: print("positivo"); total += x</code></td> <td style="border: 1px solid #ccc; padding: 4px;"><code>if x > 0:<br> print("positivo")<br> total += x</code></td> <td style="border: 1px solid #ccc; padding: 4px;">❌ No</td> </tr> <tr> <td style="border: 1px solid #ccc; padding: 4px;">Condición con ternario claro</td> <td style="border: 1px solid #ccc; padding: 4px;"><code>mensaje = "ok" if status == 200 else "error"</code></td> <td style="border: 1px solid #ccc; padding: 4px;"><code>mensaje = "ok" if status == 200 else "error"</code></td> <td style="border: 1px solid #ccc; padding: 4px;">✅ Sí</td> </tr> <tr> <td style="border: 1px solid #ccc; padding: 4px;">Condición ternaria confusa o larga</td> <td style="border: 1px solid #ccc; padding: 4px;"><code>msg = "bienvenido" if u_activo and not bloqueado and permiso else "denegado"</code></td> <td style="border: 1px solid #ccc; padding: 4px;"><code>if u_activo and not bloqueado and permiso:<br> msg = "bienvenido"<br>else:<br> msg = "denegado"</code></td> <td style="border: 1px solid #ccc; padding: 4px;">❌ No</td> </tr> <tr> <td style="border: 1px solid #ccc; padding: 4px;">Uso de <code>if / elif / else</code></td> <td style="border: 1px solid #ccc; padding: 4px;"><code>if x > 0: print("positivo") elif x < 0: print("negativo") else: print("cero")</code></td> <td style="border: 1px solid #ccc; padding: 4px;"><code>if x > 0:<br> print("positivo")<br>elif x < 0:<br> print("negativo")<br>else:<br> print("cero")</code></td> <td style="border: 1px solid #ccc; padding: 4px;">❌ No</td> </tr> </tbody> </table> --- # Conditionals **Ejercicios** <a href="python_ejercicios_conditionals.html" target= "_blank" style="color:green">Ejercicios Condicionales</a> Mas complejos <a href="python_ejercicios_conditionals_not.html" target= "_blank" style="color:green">Ejercicios Avanzados Condicionales</a>