Измените файл tuple_length.py
, добавив следующий код:
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)
В этом коде мы определяем функцию check_tuple_length
, которая принимает два аргумента: кортеж (my_tuple
) и желаемую длину (desired_length
). Функция использует функцию len()
для получения длины кортежа и затем сравнивает ее с желаемой длиной. Если длины совпадают, она выводит "The tuple has the desired length." В противном случае она выводит "The tuple does not have the desired length."
Затем мы приводим два примера использования функции. В первом примере мы создаем кортеж my_tuple
с тремя элементами и устанавливаем desired_length
равным 3. Во втором примере мы создаем кортеж another_tuple
с четырьмя элементами и также устанавливаем desired_length
равным 3.
Теперь полный файл tuple_length.py
должен выглядеть следующим образом:
## 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)
Запустите скрипт еще раз:
python ~/project/tuple_length.py
Вы должны увидеть следующий вывод:
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.
Этот вывод показывает, как можно использовать функцию len()
для сравнения длины кортежа с желаемой длиной и предпринимать разные действия в зависимости от результата.