当前分类:300例题>>正文

Python示例:检查元组中存在的项目

来源:互联网   更新时间:2023年6月23日  

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)

虽然上面的例子返回真或假,我们需要一个有意义的消息。因此,如果元组中存在条目,我们使用 if 语句和 in 运算符(numTuple 中的 If 数字)来打印不同的消息。

# 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
>>> 

使用 For 循环检查元组中是否存在项目的 Python示例

在这个 Python 示例中,我们使用 if 语句(if val == number)对照给定的数字检查每个元组项。如果为真,则结果为真,编译器将从 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
本文固定链接:https://6yhj.com/leku-p-4418.html  版权所有,转载请保留本地址!
[猜你喜欢]

标签: claude