简体   繁体   中英

Loop with 2 Conditions. (For Loop)

I have a question below. I have an array for example:

ex_ar=[1,2,3]

and I have an step size, for example:

step=5

I want to create a loop so that it should print each element during the step size. In this example here it should look like this:

1
2
3
1
2
ex_ar=[1,2,3]
step=6
for i in range(step):
    print(sayi[i])

IndexError: list index out of range

Use modulo list size

ex_ar=[1,2,3]
step=5
for i in range(step):
    print(ex_ar[i % len(ex_ar)])

You can't add two conditions on the for loop.

Alternative solution:

arr = [1,2,3]
for i in range(5):
    print(arr[i%len(arr)])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM