首页 > 编程知识 正文

Python 程序:检查元组中存在的项目

时间:2023-11-25 09:12:52 阅读:308938 作者:IBUF

编写一个 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

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。