Tracks
/
Python
Python
/
Temario
/
Condicionales
Co

Condicionales en Python

94 ejercicios

Acerca de Condicionales

En Python, las instrucciones if, elif (una contracción de «else and if») y else se usan para controlar el flujo de la ejecución y tomar decisiones en un programa. A diferencia de muchos otros lenguajes de programación, las versiones de Python 3.9 y anteriores no ofrecen una instrucción formal de tipo switch-case, sino que usan varias instrucciones elif para cumplir un propósito similar.

Python 3.10 introduce una variante de la instrucción switch-case llamada pattern matching, que se tratará por separado en otro concepto.

Las instrucciones condicionales usan expresiones que deben resolverse a True o False, ya sea devolviendo un bool directamente o evaluando si son «truthy» o «falsy».

x = 10
y = 5

# The comparison '>' returns the bool 'True',
# so the statement is printed.
if x > y:
    print("x is greater than y")
...
>>> x is greater than y

Cuando se combina con if, un bloque de código else opcional se ejecutará cuando la condición del if original se evalúe a False:

x = 5
y = 10

# The comparison '>' here returns the bool False,
# so the 'else' block is executed instead of the 'if' block.
if x > y:
    print("x is greater than y")
else:
    print("y is greater than x")
...
>>> y is greater than x

elif permite varias evaluaciones o ramas.

x = 5
y = 10
z = 20

# The elif statement allows for the checking of more conditions.
if x > y > z:
    print("x is greater than y and z")
elif y > x > z:
    print("y is greater than x and z")
else:
    print("z is greater than x and y")
...
>>> z is greater than x and y

Las operaciones booleanas y las comparaciones se pueden combinar con condicionales para hacer comprobaciones más complejas:

>>> def classic_fizzbuzz(number):
...     if number % 3 == 0 and number % 5 == 0:
...         say = 'FizzBuzz!'
...     elif number % 5 == 0:
...         say = 'Buzz!'
...     elif number % 3 == 0:
...         say = 'Fizz!'
...     else:
...         say = str(number)
...
...     return say
        
>>> classic_fizzbuzz(15)
'FizzBuzz!'

>>> classic_fizzbuzz(13)
'13'

Como alternativa, el ejemplo anterior se puede reescribir para usar solo instrucciones if con returns. Sin embargo, reescribirlo de esta forma podría ocultar que las condiciones pretenden ser mutuamente excluyentes y podría dar lugar a futuros errores o problemas de mantenimiento.

>>> def classic_fizzbuzz(number):
...     if number % 3 == 0 and number % 5 == 0:
...         return 'FizzBuzz!'
...     if number % 5 == 0:
...         return 'Buzz!'
...     if number % 3 == 0:
...         return 'Fizz!'
...
...     return str(number)

>>> classic_fizzbuzz(15)
'FizzBuzz!'

>>> classic_fizzbuzz(13)
'13'

Los condicionales también se pueden anidar.

>>> def driving_status(driver_age, test_score):
...     if test_score >= 80:
...         if 18 > driver_age >= 16:
...             status = "Student driver, needs supervision."
...         elif driver_age == 18:
...             status = "Permitted driver, on probation."
...         elif driver_age > 18:
...             status = "Fully licensed driver."
...     else:
...         status = "Unlicensed!"
...
...     return status


>>> driving_status(63, 78)
'Unlicensed!'

>>> driving_status(16, 81)
'Student driver, needs supervision.'

>>> driving_status(23, 80)
'Fully licensed driver.'

Expresiones condicionales o «operadores ternarios»

Aunque Python no tiene un operador ternario ? específico, es posible escribir conditional expressions de una sola línea. Estas adoptan la forma <value if True> if <conditional test> else <value if False>. Como estas expresiones pueden volverse difíciles de leer, se recomienda usar esta forma de una sola línea solo si acorta el código y ayuda a la legibilidad.

>>> def just_the_buzz(number):
...     return 'Buzz!' if number % 5 == 0 else str(number)
    
>>> just_the_buzz(15)
'Buzz!'

>>> just_the_buzz(7)
'7'

Truthy y falsy

En Python, se puede comprobar el valor de verdad de cualquier objeto, por lo que se puede usar con una operación condicional, de comparación o booleana. Los objetos que se evalúan de esta forma se consideran «truthy» o «falsy», y se usan en un boolean context.

>>> def truthy_test(thing):
...     if thing:
...         print('This is Truthy.')
...     else:
...         print("Nope. It's Falsy.")


# Empty container objects are considered Falsy.
>>> truthy_test([])
"Nope. It's Falsy."

>>> truthy_test(['bear', 'pig', 'giraffe'])
'This is Truthy.'

# Empty strings are considered Falsy.
>>> truthy_test('')
"Nope. It's Falsy."

>>> truthy_test('yes')
'This is Truthy.'

# 0 is also considered Falsy.
>>> truthy_test(0)
"Nope. It's Falsy."
Editar en GitHub El enlace se abre en una nueva ventana o pestaña

Aprende Condicionales

La práctica está bloqueada

Desbloquea 4 ejercicios más para practicar Condicionales