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

前端 未结 3 722
眼角桃花
眼角桃花 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 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.

提交回复
热议问题