for i in range(start,stop,step) Python 3

后端 未结 2 1911
星月不相逢
星月不相逢 2021-01-20 19:09

I want to list a range of numbers and I\'m using the \"for i in range(start,stop,step)\".

def range():
    P=36
    for i in range(P+1,0,-1):
        P=P-4
          


        
相关标签:
2条回答
  • 2021-01-20 19:44

    What's happening is that using range, creates you a list from 36 to 0 at the beggining and does a for loop 37 times. Your var P has no longer effect on the number of loops if you change it in your loop.

    In your first case you'll have 36-37*4 = -112

    In your second case you have your loop executed 9 times thats why you get 0 36 -9*4 = 0 :)

    Try using xrange it should create a value for each loop and i think it will stop at 0.

    0 讨论(0)
  • 2021-01-20 19:47

    To create a list from 36 to 0 counting down in steps of 4, you simply use the built-in range function directly:

    l = list(range(36,-1,-4)) 
    # result: [36, 32, 28, 24, 20, 16, 12, 8, 4, 0]
    

    The stop value is -1 because the loop runs from the start value (inclusive) to the stop value (exclusive). If we used 0 as stop value, the last list item would be 4.

    Or if you prefer a for loop, e.g. because you want to print the variable inside it:

    for P in range(36,-1,-4):
        print(P)
    
    0 讨论(0)
提交回复
热议问题