For loop with custom steps in python

后端 未结 6 2176
旧时难觅i
旧时难觅i 2020-11-29 07:48

I can make simple for loops in python like:

for i in range(10):

However, I couldn\'t figure out how to make more complex ones, which are re

6条回答
  •  天命终不由人
    2020-11-29 08:08

    You need to use a generator. You could implement this as follows:

    def stepDown(n):
        while n>1:
            yield n
            n = n/2
    
    for i in stepDown(n):
        print i # or do whatever else you wish.
    

    Note that this generalizes easily to other complicated patterns you may have in mind.

提交回复
热议问题