編寫一個 Python 程序,使用 for 循環範圍來計算元組中的正數和負數。if 條件(if (posngTuple[i] >= 0))檢查元組項是否大於或等於零。如果為真,我們向正元組計數添加一個;否則(tNegativeCount = tNegativeCount+1),在負元組計數值上加 1。
# Count Positive and Negative Numbers
posngTuple = (3, -22, -44, 19, -99, -37, 4, 11, -89)
print("Positive and Negative Tuple Items = ", posngTuple)
tPositiveCount = tNegativeCount = 0
for i in range(len(posngTuple)):
if (posngTuple[i] >= 0):
tPositiveCount = tPositiveCount + 1
else:
tNegativeCount = tNegativeCount + 1
print("The Count of Positive Numbers in posngTuple = ", tPositiveCount)
print("The Count of Negative Numbers in posngTuple = ", tNegativeCount)
在這個 Python 正負示例中,我們使用 for 循環(對於 posngTuple 中的 pntup)來迭代實際的元組值,並檢查它們是否大於或等於零。
# Count Positive and Negative Numbers
posngTuple = (55, -99, -88, 0, -78, 22, 4, -66, 21, 33)
print("Positive and Negative Tuple Items = ", posngTuple)
tPositiveCount = tNegativeCount = 0
for pntup in posngTuple:
if(pntup >= 0):
tPositiveCount = tPositiveCount + 1
else:
tNegativeCount = tNegativeCount + 1
print("The Count of Positive Numbers in posngTuple = ", tPositiveCount)
print("The Count of Negative Numbers in posngTuple = ", tNegativeCount)
Positive and Negative Tuple Items = (55, -99, -88, 0, -78, 22, 4, -66, 21, 33)
The Count of Positive Numbers in posngTuple = 6
The Count of Negative Numbers in posngTuple = 4
Python 程序使用 While 循環計算元組中的正數和負數。
# Count of Tuple Positive and Negative Numbers
posngTuple = (11, -22, -33, 44, 55, -66, -77, 0, -99)
print("Positive and Negative Tuple Items = ", posngTuple)
tPositiveCount = tNegativeCount = 0
i = 0
while (i < len(posngTuple)):
if(posngTuple[i] >= 0):
tPositiveCount = tPositiveCount + 1
else:
tNegativeCount = tNegativeCount + 1
i = i + 1
print("The Count of Positive Numbers in posngTuple = ", tPositiveCount)
print("The Count of Negative Numbers in posngTuple = ", tNegativeCount)
Positive and Negative Tuple Items = (11, -22, -33, 44, 55, -66, -77, 0, -99)
The Count of Positive Numbers in posngTuple = 4
The Count of Negative Numbers in posngTuple = 5
在這個 Python Tuple 示例中,我們創建了一個返回正數和負數計數的函數。
# Count of Tuple Positive and Negative Numbers
def CountOfPositiveNegativeNumbers(evodTuple):
tPositiveCount = tNegativeCount = 0
for pntup in evodTuple:
if(pntup >= 0):
tPositiveCount = tPositiveCount + 1
else:
tNegativeCount = tNegativeCount + 1
return tPositiveCount, tNegativeCount
evodTuple = (26, -77, -99, 75, 14, -56, 19, 81, -1, 33)
print("Positive and Negative Tuple Items = ", evodTuple)
PositiveCount, NegativeCount = CountOfPositiveNegativeNumbers(evodTuple)
print("The Count of Positive Numbers in evodTuple = ", PositiveCount)
print("The Count of Negative Numbers in evodTuple = ", NegativeCount)
Positive and Negative Tuple Items = (26, -77, -99, 75, 14, -56, 19, 81, -1, 33)
The Count of Positive Numbers in evodTuple = 6
The Count of Negative Numbers in evodTuple = 4
原創文章,作者:簡單一點,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/127221.html