編寫一個 Python 程序來列印集合中的正數或項目。for 循環(PositiveSet 中的 posival)內的 if 語句(if(posival > = 0))檢查 Set 項是否大於或等於零。如果為真,則列印該正數。
# Set Positive Numbers
PositiveSet = {7, -8, -11, 4, -85, 14, -22, 78, 11}
print("Positive Set Items = ", PositiveSet)
print("\nThe Positive Numbers in this PositiveSet Set are:")
for posVal in PositiveSet:
if(posVal >= 0):
print(posVal, end = " ")
在 Python 集中列印正數輸出
Positive Set Items = {4, 7, -22, 11, -85, 14, 78, -11, -8}
The Positive Numbers in this PositiveSet Set are:
4 7 11 14 78
在這個 Python 程序中,我們允許您輸入集合項目並在集合中列印正數。
# Set Positive Numbers
positiveSet = set()
number = int(input("Enter the Total Positive Set Items = "))
for i in range(1, number + 1):
value = int(input("Enter the %d Set Item = " %i))
positiveSet.add(value)
print("Positive Set Items = ", positiveSet)
print("\nThe Positive Numbers in this positiveSet Set are:")
for posVal in positiveSet:
if(posVal >= 0):
print(posVal, end = " ")
Python 列印正片集項目輸出
Enter the Total Positive Set Items = 4
Enter the 1 Set Item = -32
Enter the 2 Set Item = 23
Enter the 3 Set Item = -99
Enter the 4 Set Item = 77
Positive Set Items = {-32, 77, -99, 23}
The Positive Numbers in this positiveSet Set are:
77 23
在這個 Python Set 的例子中,我們創建了一個 setPositiveNumbers 函數來查找和列印正數。
# Set Positive Numbers
def setPositiveNumbers(positiveSet):
for posVal in positiveSet:
if(posVal >= 0):
print(posVal, end = " ")
positiveSet = set()
number = int(input("Enter the Total Positive Set Items = "))
for i in range(1, number + 1):
value = int(input("Enter the %d Set Item = " %i))
positiveSet.add(value)
print("Positive Set Items = ", positiveSet)
print("\nThe Positive Numbers in this positiveSet Set are:")
setPositiveNumbers(positiveSet)
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/245159.html