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

编写一个 Python 程序,使用 for 循环 range (for i in range(len(evodTuple))) 来计算元组中的偶数和奇数个数。if 条件 (if(evodTuple[i] % 2 == 0)) 检查元组项是否能被二整除。如果为 True,我们将偶数元组计数加一;否则,我们将奇数元组计数加一。

# Count of Tuple Even and Odd Numbers

evodTuple = (2, 33, 45, 88, 77, 98, 54, 0, 17)
print("Even and Odd Tuple Items = ", evodTuple)

tEvenCount = tOddCount = 0

for i in range(len(evodTuple)):
    if(evodTuple[i] % 2 == 0):
        tEvenCount = tEvenCount + 1
    else:
        tOddCount = tOddCount + 1

print("The Count of Even Numbers in evodTuple = ", tEvenCount)
print("The Count of Odd  Numbers in evodTuple = ", tOddCount)
Python Program to Count Even and Odd Numbers in Tuple

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

在此 Python 示例中,我们使用了 for 循环 (for oetup in evodTuple) 来迭代实际的元组值,并检查它们是否能被二整除且余数为零。

# Count of Tuple Even and Odd Numbers

evodTuple = (11, 34, 17, 44, 66, 19, 89, 64, 90)
print("Even and Odd Tuple Items = ", evodTuple)

tEvenCount = tOddCount = 0
for oetup in evodTuple:
    if(oetup % 2 == 0):
        tEvenCount = tEvenCount + 1
    else:
        tOddCount = tOddCount + 1

print("The Count of Even Numbers in evodTuple = ", tEvenCount)
print("The Count of Odd  Numbers in evodTuple = ", tOddCount)
Even and Odd Tuple Items =  (11, 34, 17, 44, 66, 19, 89, 64, 90)
The Count of Even Numbers in evodTuple =  5
The Count of Odd  Numbers in evodTuple =  4

Python 程序使用 While 循环计算元组的偶数和奇数。

# Count of Tuple Even and Odd Numbers

evodTuple = (64, 45, 12, 15, 68, 55, 37, 25, 120, 205)
print("Even and Odd Tuple Items = ", evodTuple)

tEvenCount = tOddCount = 0
i = 0

while (i < len(evodTuple)):
    if(evodTuple[i] % 2 == 0):
        tEvenCount = tEvenCount + 1
    else:
        tOddCount = tOddCount + 1
    i = i + 1

print("The Count of Even Numbers in evodTuple = ", tEvenCount)
print("The Count of Odd  Numbers in evodTuple = ", tOddCount)
Even and Odd Tuple Items =  (64, 45, 12, 15, 68, 55, 37, 25, 120, 205)
The Count of Even Numbers in evodTuple =  4
The Count of Odd  Numbers in evodTuple =  6

在此 Python 元组 示例中,我们创建了一个 CountOfEvenOddOddNumbers 函数,该函数返回偶数和奇数的计数。

# Count of Tuple Even and Odd Numbers

def CountOfEvenOddOddNumbers(evodTuple):
    tEvenCount = tOddCount = 0
    for oetup in evodTuple:
        if(oetup % 2 == 0):
            tEvenCount = tEvenCount + 1
        else:
            tOddCount = tOddCount + 1
    return tEvenCount, tOddCount

evodTuple = (12, 26, 77, 99, 66, 75, 14, 256, 19, 81, 11, 33) 
print("Even and Odd Tuple Items = ", evodTuple)

evenCount, oddCount = CountOfEvenOddOddNumbers(evodTuple)
print("The Count of Even Numbers in evodTuple = ", evenCount)
print("The Count of Odd  Numbers in evodTuple = ", oddCount)
Even and Odd Tuple Items =  (12, 26, 77, 99, 66, 75, 14, 256, 19, 81, 11, 33)
The Count of Even Numbers in evodTuple =  5
The Count of Odd  Numbers in evodTuple =  7