当前分类:300例题>>正文

Python示例:打印集合中的偶数

来源:互联网   更新时间:2023年6月24日  

Python 示例

写一个 Python示例来打印集合中的偶数。if 语句(if(val % 2 == 0))测试 Set 项是否可被 2 整除,并返回零。如果为真,则在集合中打印该偶数。

# Set Even Numbers

evSet = {15, 26, 19, 78, 64, 35, 66}
print("Even Set Items = ", evSet)

print("\nThe Even Numbers in this evSet Set are:")
for val in evSet:
    if(val % 2 == 0):
        print(val, end = "  ")

在 Python 集中打印偶数输出

Even Set Items =  {64, 66, 35, 19, 26, 78, 15}

The Even Numbers in this evSet Set are:
64  66  26  78 

这个 Python 集合程序允许输入集合项目并打印偶数。

# Set Even Numbers

evSet = set()

number = int(input("Enter the Total Even Set Items = "))
for i in range(1, number + 1):
    value = int(input("Enter the %d Set Item = " %i))
    evSet.add(value)

print("Even Set Items = ", evSet)

print("\nThe Even Numbers in this evSet Set are:")
for val in evSet:
    if(val % 2 == 0):
        print(val, end = "  ")

在这个 Python Set 的例子中,我们创建了一个 setEvenNumbers 函数,它打印偶数。

# Set Even Numbers

def setEvenNumbers(evset):
    for val in evSet:
        if(val % 2 == 0):
            print(val, end = "  ")

evSet = set()

number = int(input("Enter the Total Even Set Items = "))
for i in range(1, number + 1):
    value = int(input("Enter the %d Set Item = " %i))
    evSet.add(value)

print("Even Set Items = ", evSet)

print("\nThe Even Numbers in this evSet Set are:")
setEvenNumbers(evSet)
Enter the Total Even Set Items = 7
Enter the 1 Set Item = 22
Enter the 2 Set Item = 33
Enter the 3 Set Item = 44
Enter the 4 Set Item = 55
Enter the 5 Set Item = 66
Enter the 6 Set Item = 77
Enter the 7 Set Item = 89
Even Set Items =  {33, 66, 44, 77, 22, 55, 89}

The Even Numbers in this evSet Set are:
66  44  22 
本文固定链接:https://6yhj.com/leku-p-4450.html  版权所有,转载请保留本地址!
[猜你喜欢]

标签: 百度统计