Modifiez le fichier tuple_length.py
pour inclure le code suivant :
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)
Dans ce code, nous définissons une fonction appelée check_tuple_length
qui prend deux arguments : un tuple (my_tuple
) et une longueur souhaitée (desired_length
). La fonction utilise la fonction len()
pour obtenir la longueur du tuple, puis la compare avec la longueur souhaitée. Si les longueurs correspondent, elle affiche "The tuple has the desired length." Sinon, elle affiche "The tuple does not have the desired length."
Nous fournissons ensuite deux exemples d'utilisation de la fonction. Dans le premier exemple, nous créons un tuple my_tuple
avec trois éléments et définissons la desired_length
à 3. Dans le deuxième exemple, nous créons un tuple another_tuple
avec quatre éléments et définissons la desired_length
à 3.
Le fichier tuple_length.py
complet devrait maintenant ressembler à ceci :
## 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)
Exécutez le script à nouveau :
python ~/project/tuple_length.py
Vous devriez voir la sortie suivante :
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.
Cette sortie démontre comment vous pouvez utiliser la fonction len()
pour comparer la longueur d'un tuple avec une longueur souhaitée et prendre différentes actions en fonction du résultat.