Home > OS >  Loop with 2 Conditions. (For Loop)
Loop with 2 Conditions. (For Loop)

Time:12-13

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

CodePudding user response:

Use modulo list size

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

CodePudding user response:

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)])
  • Related