Python 程序打印元组中的负数

编写一个 Python 程序,使用 for 循环 range 打印元组中的负数。if 语句 (if(negTuple[i] < 0)) 检查元组项是否小于零。如果为 True,则打印该负元组数 (print(negTuple[i], end = ” “))。

# Tuple Negative Numbers

negTuple = (3, -8, -22, 4, -98, 14, -33, -78, 11)
print("Negative Tuple Items = ", negTuple)

print("\nThe Negative Numbers in negTuple Tuple are:")
for i in range(len(negTuple)):
    if(negTuple[i] < 0):
        print(negTuple[i], end = "  ")
Negative Tuple Items =  (3, -8, -22, 4, -98, 14, -33, -78, 11)

The Negative Numbers in negTuple Tuple are:
-8  -22  -98  -33  -78 

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

在此 Python 负数示例中,我们使用 for 循环 (for ngtup in negTuple) 来迭代实际的元组项。

# Tuple Negative Numbers

negTuple = (25, -14, -28, 17, -61, -21, 89, 17, -48, 0)
print("Negative Tuple Items = ", negTuple)

print("\nThe Negative Numbers in this negTuple Tuple are:")
for ngtup in negTuple:
    if(ngtup < 0):
        print(ngtup, end = "  ")
Negative Tuple Items =  (25, -14, -28, 17, -61, -21, 89, 17, -48, 0)

The Negative Numbers in this negTuple Tuple are:
-14  -28  -61  -21  -48  

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

# Tuple Negative Numbers

negTuple = (11, -22, -45, 67, -98, -87, 0, 16, -120) 
print("Negative Tuple Items = ", negTuple)

i = 0

print("\nThe Negative Numbers in negTuple Tuple are:")
while (i < len(negTuple)):
    if(negTuple[i] < 0):
        print(negTuple[i], end = "  ")
    i = i + 1
Negative Tuple Items =  (11, -22, -45, 67, -98, -87, 0, 16, -120)

The Negative Numbers in negTuple Tuple are:
-22  -45  -98  -87  -120 

在此 Python 元组 示例 中,我们创建了一个函数 (tupleNegativeNumbers(negTuple)) 来查找并打印负数。

# Tuple Negative Numbers

def tupleNegativeNumbers(negTuple):
    for potup in negTuple:
        if(potup < 0):
            print(potup, end = "  ")


negTuple = (9, -23, -17, 98, 66, -12, -77, 0, -2, 15) 
print("Negative Tuple Items = ", negTuple)

print("\nThe Negative Numbers in negTuple Tuple are:")
tupleNegativeNumbers(negTuple)
Python Program to Print Negative Numbers in Tuple 4