Enos jeba
Enos jeba

Reputation: 132

Is there a way to repeat 'A number in the middle of a loop' multiple times?

Let's say this is a loop I am aiming for, Starting with 10 and ending at 6.

for i in range(10,6,-1):
        print(i)

But I want to print 8 multiple times.

so if the loop is going on downhill, Is there a way to stop at a certain point and repeat just the value again and again for N number of times?

Upvotes: 0

Views: 377

Answers (3)

user1196549
user1196549

Reputation:

For a solution with a single loop body,

for i in range(10, 5 - 2, -1):
    j= i + min(2, max(0, 8 - i))
    print(j)

You can replace 8 by another number to be repeated and 2 by another repetition count.

Upvotes: 0

Mortz
Mortz

Reputation: 4939

You can also think of doing the same with a while block -

loop_range = range(10, 6, -1)
it = iter(loop_range)
while True:
    try:
        item = next(it)
        if item == 8:
            print(*[item]*3, sep='\n')
        print(item)
    except StopIteration:
        break

The same construct can be made more terse and more readable using a generator expression -

custom_sequence = ((_,)*3 if _ == 8 else (_,) for _ in range(10, 6, -1))
for i in custom_sequence:
    print(*i, sep='\n')

Upvotes: 0

Devang Sanghani
Devang Sanghani

Reputation: 780

Very simple one with hard-cording:

for i in range(10,5,-1):
        if i == 8:
            for _ in range(3):
                print(i)
        else:
            print(i)

Output:

10
9
8
8
8
7
6

Upvotes: 1

Related Questions