您的位置:

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)