Python程序:计算元组项和

创新互联Python教程:

编写一个 Python 程序来查找元组中所有项目的总和。这里,我们使用 Tuple sum 函数返回所有 Tuple 项的总和。

# Tuple Sum of All Items

numTuple = (20, 40, 65, 75, 80, 220)
print("Tuple Items = ", numTuple)

tupleSum = sum(numTuple)
print("\nThe Sum of numTuple Tuple Items = ", tupleSum)
Tuple Items =  (20, 40, 65, 75, 80, 220)

The Sum of numTuple Tuple Items =  500

寻找元组项之和的 Python 程序

在这个 Python 示例中,for 循环(用于 numTuple 中的 tup)迭代所有元组项。在循环(tupleSum = tupleSum + tup)中,我们将每个元组项添加到 tupleSum 中,并打印相同的内容。

# Tuple Sum of All Items

numTuple = (11, 22, 33, 44, 55, 66, 77, 88, 99)
print("Odd Tuple Items = ", numTuple)

tupleSum = 0
for tup in numTuple:
    tupleSum = tupleSum + tup

print("\nThe Sum of numTuple Tuple Items = ", tupleSum)
Odd Tuple Items =  (11, 22, 33, 44, 55, 66, 77, 88, 99)

The Sum of numTuple Tuple Items =  495

Python 程序使用 While 循环计算所有元组项的总和。

# Tuple Sum of All Items

numTuple = (25, 45, 65, 75, 95, 125, 256, 725)
print("Odd Tuple Items = ", numTuple)

tupleSum = 0
i = 0

while (i < len(numTuple)):
    tupleSum = tupleSum + numTuple[i]
    i = i + 1

print("\nThe Sum of numTuple Tuple Items = ", tupleSum)
Odd Tuple Items =  (25, 45, 65, 75, 95, 125, 256, 725)

The Sum of numTuple Tuple Items =  1411

在这个 Python Tuple 示例中,我们创建了一个 sumOfTupleItems(numTuple)函数,该函数将计算并返回所有 tuple 项的总和。

# Tuple Sum

def sumOfTupleItems(numTuple):
    tupleSum = 0
    for tup in numTuple:
        tupleSum = tupleSum + tup
    return tupleSum

numTuple = (16, 31, 24, 98, 123, 78, 56, 67, 22)
print("Tuple Items = ", numTuple)

tSum = sumOfTupleItems(numTuple)
print("\nThe Sum of numTuple Tuple Items = ", tSum)

新闻名称:Python程序:计算元组项和
文章网址:http://www.csdahua.cn/qtweb/news36/424836.html

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

广告

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