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

创新互联python教程:

创新互联是一家专业提供宁河企业网站建设,专注与成都做网站、网站设计、外贸营销网站建设成都h5网站建设、小程序制作等业务。10年已为宁河众多企业、政府机构等服务。创新互联专业网站制作公司优惠进行中。

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

当前文章:Python 程序:检查元组中存在的项目
文章链接:http://www.shufengxianlan.com/qtweb/news42/22042.html

网站建设、网络推广公司-创新互联,是专注品牌与效果的网站制作,网络营销seo公司;服务项目有等

广告

声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 创新互联