您的位置:

Python 程序:打印元组中正数

编写一个 Python 程序,使用 for 循环范围打印元组中的正数。if 语句(if(posTuple[i] >= 0))检查元组项是否大于或等于零。如果为真,则打印正元组编号。

# Tuple Positive Numbers

posTuple = (3, -8, 6, 4, -88, -11, 13, 19)
print("Positive Tuple Items = ", posTuple)

print("\nThe Positive Numbers in posTuple Tuple are:")
for i in range(len(posTuple)):
    if(posTuple[i] >= 0):
        print(posTuple[i], end = "  ")
Positive Tuple Items =  (3, -8, 6, 4, -88, -11, 13, 19)

The Positive Numbers in posTuple Tuple are:
3  6  4  13  19 

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

在这个 Python 正数示例中,我们使用 for 循环(用于后置元组中的 potup)来迭代实际的元组后置项。

# Tuple Positive Numbers

posTuple = (25, 32, -14, 17, -6, -1, 98, 11, -9, 0)
print("Positive Tuple Items = ", posTuple)

print("\nThe Positive Numbers in this posTuple Tuple are:")
for potup in posTuple:
    if(potup >= 0):
        print(potup, end = "  ")
Positive Tuple Items =  (25, 32, -14, 17, -6, -1, 98, 11, -9, 0)

The Positive Numbers in this posTuple Tuple are:
25  32  17  98  11  0 

Python 程序使用 While 循环返回或显示元组中的正数。

# Tuple Positive Numbers

posTuple = (25, -11, -22, 17, 0, -9, 43, 17, -10) 
print("Positive Tuple Items = ", posTuple)

i = 0

print("\nThe Positive Numbers in posTuple Tuple are:")
while (i < len(posTuple)):
    if(posTuple[i] >= 0):
        print(posTuple[i], end = "  ")
    i = i + 1
Positive Tuple Items =  (25, -11, -22, 17, 0, -9, 43, 17, -10)

The Positive Numbers in posTuple Tuple are:
25  17  0  43  17 

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

# Tuple Positive Numbers

def tuplePositiveNumbers(posTuple):
    for potup in posTuple:
        if(potup >= 0):
            print(potup, end = "  ")

posTuple = (19, -32, -17, 98, 44, -12, 0, 78, -2, 4, -5) 
print("Positive Tuple Items = ", posTuple)

print("\nThe Positive Numbers in this posTuple Tuple are:")
tuplePositiveNumbers(posTuple)