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
という関数を定義しています。この関数は 2 つの引数を取ります。1 つはタプル (my_tuple
)、もう 1 つは目標の長さ (desired_length
) です。関数は len()
関数を使ってタプルの長さを取得し、それを目標の長さと比較します。長さが一致する場合、「The tuple has the desired length.」と出力します。そうでない場合、「The tuple does not have the desired length.」と出力します。
その後、この関数の使用例を 2 つ示しています。最初の例では、3 つの要素を持つタプル my_tuple
を作成し、desired_length
を 3 に設定しています。2 番目の例では、4 つの要素を持つタプル 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)