Python 程序检查项是否存在于元组中

编写一个 Python 程序来检查给定项是否存在于元组中。我们使用 `in` 运算符来查找存在于元组中的项。

# Check Element Presnet in Tuple

numTuple = (4, 6, 8, 11, 22, 43, 58, 99, 16)
print("Tuple Items = ", numTuple)

number = int(input("Enter Tuple Item to Find = "))

result = number in numTuple

print("Does our numTuple Contains the ", number, "? ", result)
Python Program to Check Item exists in Tuple 1

虽然上面的例子返回 True 或 False,但我们需要一个有意义的消息。因此,我们使用 `if` 语句和 `in` 运算符(if number in numTuple)来在项存在于元组中时打印不同的消息。

# Check Element Presnet in Tuple

numTuple = (4, 6, 8, 11, 22, 43, 58, 99, 16)
print("Tuple Items = ", numTuple)

number = int(input("Enter Tuple Item to Find = "))

if number in numTuple:
    print(number, " is in the numTuple")
else:
    print("Sorry! We haven't found ", number, " in numTuple")
Tuple Items =  (4, 6, 8, 11, 22, 43, 58, 99, 16)
Enter Tuple Item to Find = 22
22  is in the numTuple
>>> 
Tuple Items =  (4, 6, 8, 11, 22, 43, 58, 99, 16)
Enter Tuple Item to Find = 124
Sorry! We haven't found  124  in numTuple
>>> 

Python 程序使用 For 循环检查项是否存在于元组中

在此 示例 中,我们使用 `if` 语句(if val == number)将每个 元组 项与给定的数字进行比较。如果为真,则结果为 True,并且编译器将从 for 循环中退出。

# Check Element Presnet in Tuple

numTuple = (4, 6, 8, 11, 22, 43, 58, 99, 16)
print("Tuple Items = ", numTuple)

number = int(input("Enter Tuple Item to Find = "))

result = False

for val in numTuple:
    if val == number:
        result = True
        break

print("Does our numTuple Contains the ", number, "? ", result)
Tuple Items =  (4, 6, 8, 11, 22, 43, 58, 99, 16)
Enter Tuple Item to Find = 16
Does our numTuple Contains the  16 ?  True