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

Python示例:计算元组项和

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

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)

本文固定链接:https://6yhj.com/leku-p-4421.html  版权所有,转载请保留本地址!
[猜你喜欢]

标签: 编程