我对Python很陌生,我尝试制作一个简单的程序 我试图定义一个函数,它接受任意给定数量的参数并打印给定的所有偶数 但是,我不知道如何知道给出了多少数字,主要是如何通过它们,或者更确切地说,如何制作一个检查每个数字的循环。提前谢谢!
这是我的错误代码:
def even_number_filter(*arg):
a = len(sys.argv)
for (arg % 2 == 0):
print ("\n%d is an even number") % arg
even_number_filter (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
答案 0 :(得分:2)
你可以迭代arg
本身,它只是参数的元组
def even_number_filter(*arg):
for i in arg:
if i % 2 == 0:
print('{} is an even number'.format(i))
>>> even_number_filter(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
2 is an even number
4 is an even number
6 is an even number
8 is an even number
10 is an even number
然而,为了将来参考,我会劝阻这种设计。相反,我会直接接受一些序列,例如list
或tuple
答案 1 :(得分:2)
使用set& amp;列表理解:
print {x for x in {1, 2, 3, 4, 5, 6, 7, 8, 9, 10} if x % 2 == 0}
print [x for x in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] if x % 2 == 0]
产地:
set([8, 2, 4, 10, 6])
[2, 4, 6, 8, 10]
在可能的情况下,您应该尝试使用理解(或生成器)而不是显式for循环。没有那么重要,因为你刚刚开始并尝试学习基础知识,但良好的开始有良好的习惯!
答案 2 :(得分:0)
理想情况下,将参数作为可迭代(列表或生成器)而不是varargs。然后,这是使用列表理解的理想时间:
def even_numbers(numbers):
return [
num for num in numbers
if num % 2 == 0
]
def even_number_filter(numbers):
for num in even_numbers(numbers):
print "{0} is even".format(num)
if __name__ == '__main__':
even_number_filter(range(10))
0 is even
2 is even
4 is even
6 is even
8 is even