Python 程序:打印元组中奇数

发布时间:2022-07-24

使用 for 循环打印元组中的奇数

编写一个 Python 程序,使用 for 循环范围打印元组中的奇数。for 循环使用 range(len(oddTuple)),并通过 if 语句 if(oddTuple[i] % 2 != 0) 检查每个元组项是否为奇数。如果为真,则打印该奇数。

# Tuple Odd Numbers
oddTuple = (9, 22, 33, 45, 56, 77, 89, 90)
print("Odd Tuple Items = ", oddTuple)
print("\nThe Odd Numbers in oddTuple Tuple are:")
for i in range(len(oddTuple)):
    if(oddTuple[i] % 2 != 0):
        print(oddTuple[i], end = "  ")

输出结果:

Odd Tuple Items =  (9, 22, 33, 45, 56, 77, 89, 90)
The Odd Numbers in oddTuple Tuple are:
9  33  45  77  89 

使用 For 循环打印元组中奇数的 Python 程序

在这个 Python 奇数示例中,我们使用 for 循环 for tup in oddTuple 来迭代实际的元组项以找到奇数。

# Tuple Odd Numbers
oddTuple = (19, 98, 17, 23, 56, 77, 88, 99, 111)
print("Tuple Items = ", oddTuple)
print("\nThe Odd Numbers in this oddTuple Tuple are:")
for tup in oddTuple:
    if(tup % 2 != 0):
        print(tup, end = "  ")

输出结果:

Tuple Items =  (19, 98, 17, 23, 56, 77, 88, 99, 111)
The Odd Numbers in this oddTuple Tuple are:
19  17  23  77  99  111 

Python 程序使用 while 循环返回元组中的奇数。

# Tuple Odd Numbers
oddTuple = (25, 19, 44, 53, 66, 79, 89, 22, 67) 
print("Odd Tuple Items = ", oddTuple)
i = 0
print("\nThe Odd Numbers in oddTuple Tuple are:")
while (i < len(oddTuple)):
    if(oddTuple[i] % 2 != 0):
        print(oddTuple[i], end = "  ")
    i = i + 1

输出结果:

Odd Tuple Items =  (25, 19, 44, 53, 66, 79, 89, 22, 67)
The Odd Numbers in oddTuple Tuple are:
25  19  53  79  89  67 

在这个 Python Tuple 示例中,我们创建了一个函数 tupleOddNumbers(oddTuple) 来查找和打印奇数。

# Tuple Odd Numbers
def tupleOddNumbers(oddTuple):
    for tup in oddTuple:
        if(tup % 2 != 0):
            print(tup, end = "  ")
oddTuple = (122, 55, 12, 11, 67, 88, 42, 99, 17, 64) 
print("Tuple Items = ", oddTuple)
print("\nThe Odd Numbers in oddTuple Tuple are:")
tupleOddNumbers(oddTuple)