Python 程序:计算元组中奇偶数和

编写一个 Python 程序,使用 for 循环范围来查找元组中偶数和奇数的和。if 条件(if(evenodtuple[I]% 2 = = 0))检查可被二整除的 Tuple 项是否等于零。如果为真,则将该元组项添加到偶数和;否则,加到奇数和。

# Sum of Tuple Even and Odd Numbers

evenOddTuple = (9, 22, 33, 45, 56, 77, 89, 90)
print("Even and Odd Tuple Items = ", evenOddTuple)

tEvenSum = tOddSum = 0

for i in range(len(evenOddTuple)):
    if(evenOddTuple[i] % 2 == 0):
        tEvenSum = tEvenSum + evenOddTuple[i]
    else:
        tOddSum = tOddSum + evenOddTuple[i]

print("The Sum of Even Numbers in evenOddTuple = ", tEvenSum)
print("The Sum of Odd  Numbers in evenOddTuple = ", tOddSum)
Even and Odd Tuple Items =  (9, 22, 33, 45, 56, 77, 89, 90)
The Sum of Even Numbers in evenOddTuple =  168
The Sum of Odd  Numbers in evenOddTuple =  253

在这个 Python 示例中,我们使用 for 循环(用于 evenOddTuple 中的 eotup)和 If 语句(if(eotup % 2 == 0))来检查元组项是否可以被等于零的 2 整除。

# Sum of Tuple Even and Odd Numbers

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

tEvenSum = tOddSum = 0
for eotup in evenOddTuple:
    if(eotup % 2 == 0):
        tEvenSum = tEvenSum + eotup
    else:
        tOddSum = tOddSum + eotup

print("The Sum of Even Numbers in evenOddTuple = ", tEvenSum)
print("The Sum of Odd  Numbers in evenOddTuple = ", tOddSum)

Python 元组程序,使用 While 循环查找奇数和偶数的和。

# Sum of Tuple Even and Odd Numbers

evenOddTuple = (16, 25, 42, 35, 56, 55, 37, 95, 122, 205)
print("Even and Odd Tuple Items = ", evenOddTuple)

tEvenSum = tOddSum = 0
i = 0

while (i < len(evenOddTuple)):
    if(evenOddTuple[i] % 2 == 0):
        tEvenSum = tEvenSum + evenOddTuple[i]
    else:
        tOddSum = tOddSum + evenOddTuple[i]
    i = i + 1

print("The Sum of Even Numbers in evenOddTuple = ", tEvenSum)
print("The Sum of Odd  Numbers in evenOddTuple = ", tOddSum)
Even and Odd Tuple Items =  (16, 25, 42, 35, 56, 55, 37, 95, 122, 205)
The Sum of Even Numbers in evenOddTuple =  236
The Sum of Odd  Numbers in evenOddTuple =  452

在这个 Python Tuple 的例子中,我们创建了一个 sumOfEvenOddOddNumbers 函数,该函数返回奇数和偶数。

# Sum of Tuple Even and Odd Numbers

def sumOfEvenOddOddNumbers(evenOddTuple):
    tEvenSum = tOddSum = 0
    for eotup in evenOddTuple:
        if(eotup % 2 == 0):
            tEvenSum = tEvenSum + eotup
        else:
            tOddSum = tOddSum + eotup
    return tEvenSum, tOddSum

evenOddTuple = (10, 23, 20, 33, 43, 40, 60, 93, 120, 83) 
print("Even and Odd Tuple Items = ", evenOddTuple)

evenSum, oddSum = sumOfEvenOddOddNumbers(evenOddTuple)
print("The Sum of Even Numbers in evenOddTuple = ", evenSum)
print("The Sum of Odd  Numbers in evenOddTuple = ", oddSum)
Even and Odd Tuple Items =  (10, 23, 20, 33, 43, 40, 60, 93, 120, 83)
The Sum of Even Numbers in evenOddTuple =  250
The Sum of Odd  Numbers in evenOddTuple =  275

原创文章,作者:MD3DC,如若转载,请注明出处:https://www.506064.com/n/126836.html

汽车小知识 小米SU7 今日油价 油耗计算器 电耗计算器 购置税计算器 贷款计算器 保险计算器 交通违章代码 体育新闻
(0)
MD3DCMD3DC
上一篇 2024-10-03 23:13
下一篇 2024-10-03 23:13

相关推荐

发表回复

登录后才能评论