How to count by twos with Python's 'range'

前端 未结 3 721
眼角桃花
眼角桃花 2021-02-19 00:35

So imagine I want to go over a loop from 0 to 100, but skipping the odd numbers (so going \"two by two\").

for x in range(0,100):
    if x%2 == 0:
        print          


        
相关标签:
3条回答
  • 2021-02-19 00:54
    for i in range(0, 100, 2):
        print i
    

    If you are using an IDE, it tells you syntax:

    min, max, step(optional)

    0 讨论(0)
  • 2021-02-19 01:06

    Use the step argument (the last, optional):

    for x in range(0, 100, 2):
        print(x)
    

    Note that if you actually want to keep the odd numbers, it becomes:

    for x in range(1, 100, 2):
        print(x)
    

    Range is a very powerful feature.

    0 讨论(0)
  • 2021-02-19 01:09

    (Applicable to Python <= 2.7.x only)

    In some cases, if you don't want to allocate the memory to a list then you can simply use the xrange() function instead of the range() function. It will also produce the same results, but its implementation is a bit faster.

    for x in xrange(0,100,2):
        print x,   #For printing in a line
    
    >>> 0, 2, 4, ...., 98 
    

    Python 3 actually made range behave like xrange, which doesn't exist anymore.

    0 讨论(0)
提交回复
热议问题