编写一个 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
标签: chatgpt