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

后端 未结 2 1935
星月不相逢
星月不相逢 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: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)
    

提交回复
热议问题