Python: printing without overwriting print lines

I have

for i in range(0, 11): print i, "\n", i

I want my python program to print this path for every loop cycle

1st cycle:

1
1

Second cycle:

1
2
2
1

Third cycle:

1
2
3
3
2
1

I tried using \ r \ n or \ 033 [1A, but they just overwrite the previous line. Is there a way I can β€œpop” the output string so that I don't overwrite it?

+4
source share
6 answers

One way to do this,

def foo(x, limit):
        if x < limit :
                print x
                foo(x + 1, limit)
                print x

foo(1, 11)
+5
source

This cannot be done in 1 for the loop as you are trying now.

As I suggested, you can do this using these lists

>>> l1 = []
>>> l2 = []
>>> for i in range(0, 11):
...   l1.append(i)
...   l2 = [i] + l2
>>> l1.extend(l2)
>>> for i in l1:
...  print i

0
1
2
3
4
5
6
7
8
9
10
10
9
8
7
6
5
4
3
2
1
0
+1
source

.

>>> ladder = [x for x in range(5)] + [x for x in range(5,-1,-1)]
>>> ladder
[0, 1, 2, 3, 4, 5, 4, 3, 2, 1, 0]
>>> for x in ladder:
...     print x
... 
0
1
2
3
4
5
4
3
2
1
0
>>> 
+1

def two_side_print(start, end):
    text = [str(i) for i in range(start,end)]
    print '\n'.join(text), '\n', '\n'.join(reversed(text))

two_side_print(1, 11)
0

Another option is to save the printed values ​​in a list and print this list in reverse order at each iteration of the loop.

My suggestion:

l = []

for i in range(1, 5):
    print 'Loop '+str(i) # This is to ease seeing the printing results

    for val in l:
        print val

    print i
    l.insert(len(l),i)

    for val in reversed(l):
        print val

Output for a loop repeating from 0to 5:

Loop 1
1
1
Loop 2
1
2
2
1
Loop 3
1
2
3
3
2
1
Loop 4
1
2
3
4
4
3
2
1

Hope this is what you are looking for.

0
source

You can use the recursive function to help here:

def print_both_ways(start, end):
    print(start)
    if start != end:
        print_both_ways(start+1, end)

    print(start)

Using:

print_both_ways(1,3) # prints 1,2,3,3,2,1 on separate lines
0
source

Source: https://habr.com/ru/post/1606259/


All Articles