編寫一個 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
在這個 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)
原創文章,作者:簡單一點,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/127102.html