Even numbers in Python

2019-03-12 10:16发布

Does anyone know if Python has an in-built function to work to print out even values. Like range() for example.

Thanks

标签: python range
8条回答
手持菜刀,她持情操
2楼-- · 2019-03-12 10:21
>>> if 100 % 2 == 0 : print "even"
...
even
查看更多
Emotional °昔
3楼-- · 2019-03-12 10:25

Range has three parameters.

You can write range(0, 10, 2).

查看更多
相关推荐>>
4楼-- · 2019-03-12 10:25

I don't know if this is what you want to hear, but it's pretty trivial to filter out odd values with list comprehension.

evens = [x for x in range(100) if x%2 == 0]

or

evens = [x for x in range(100) if x&1 == 0]

You could also use the optional step size parameter for range to count up by 2.

查看更多
手持菜刀,她持情操
5楼-- · 2019-03-12 10:31
#This is not suggestible way to code in Python, but it gives a better understanding


numbers = range(1,10)

even = []

for i in numbers:

     if i%2 == 0:

       even.append(i)
print (even)
查看更多
淡お忘
6楼-- · 2019-03-12 10:36

Just use a step of 2:

range(start, end, step)
查看更多
小情绪 Triste *
7楼-- · 2019-03-12 10:36

Try:

range( 0, 10, 2 )
查看更多
登录 后发表回答