编写一个 Python 程序,使用 for 循环 range 打印元组中的正数。if 语句 (if(posTuple[i] >= 0)) 检查元组项是否大于等于零。如果为 True,则打印该正元组数。
# 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
Python 程序使用 For 循环打印元组中的正数。
在此 Python 正数示例中,我们使用了 for 循环 (for potup in posTuple) 来迭代实际的元组 posTuple 项。
# 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 元组 示例中,我们创建了一个函数 (tuplePositiveNumbers(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)
