Modifica el archivo tuple_length.py
para incluir el siguiente código:
def check_tuple_length(my_tuple, desired_length):
"""
Checks if the length of a tuple matches the desired length.
"""
if len(my_tuple) == desired_length:
print("The tuple has the desired length.")
else:
print("The tuple does not have the desired length.")
## Example usage:
my_tuple = (1, 2, 3)
desired_length = 3
check_tuple_length(my_tuple, desired_length)
another_tuple = ("a", "b", "c", "d")
desired_length = 3
check_tuple_length(another_tuple, desired_length)
En este código, definimos una función llamada check_tuple_length
que toma dos argumentos: una tupla (my_tuple
) y una longitud deseada (desired_length
). La función utiliza la función len()
para obtener la longitud de la tupla y luego la compara con la longitud deseada. Si las longitudes coinciden, imprime "The tuple has the desired length." De lo contrario, imprime "The tuple does not have the desired length."
Luego proporcionamos dos ejemplos de cómo usar la función. En el primer ejemplo, creamos una tupla my_tuple
con tres elementos y establecemos la desired_length
en 3. En el segundo ejemplo, creamos una tupla another_tuple
con cuatro elementos y establecemos la desired_length
en 3.
El archivo tuple_length.py
completo ahora debería verse así:
## Tuple of strings
string_tuple = ("apple", "banana", "cherry")
string_length = len(string_tuple)
print("The length of the string tuple is:", string_length)
## Tuple of mixed data types
mixed_tuple = (1, "hello", 3.14, True)
mixed_length = len(mixed_tuple)
print("The length of the mixed tuple is:", mixed_length)
## Empty tuple
empty_tuple = ()
empty_length = len(empty_tuple)
print("The length of the empty tuple is:", empty_length)
## Tuple of numbers
number_tuple = (1, 2, 3, 4, 5)
number_length = len(number_tuple)
if number_length > 3:
print("The tuple has more than 3 elements.")
else:
print("The tuple has 3 or fewer elements.")
def check_tuple_length(my_tuple, desired_length):
"""
Checks if the length of a tuple matches the desired length.
"""
if len(my_tuple) == desired_length:
print("The tuple has the desired length.")
else:
print("The tuple does not have the desired length.")
## Example usage:
my_tuple = (1, 2, 3)
desired_length = 3
check_tuple_length(my_tuple, desired_length)
another_tuple = ("a", "b", "c", "d")
desired_length = 3
check_tuple_length(another_tuple, desired_length)
Ejecuta el script nuevamente:
python ~/project/tuple_length.py
Deberías ver la siguiente salida:
The length of the string tuple is: 3
The length of the mixed tuple is: 4
The length of the empty tuple is: 0
The tuple has more than 3 elements.
The tuple has the desired length.
The tuple does not have the desired length.
Esta salida demuestra cómo puedes usar la función len()
para comparar la longitud de una tupla con una longitud deseada y tomar diferentes acciones según el resultado.