Home > Mobile >  How can I add line breaks for my output? (im super beginner)
How can I add line breaks for my output? (im super beginner)

Time:11-09

I have printed out a list of numbers, but I want to make the output 'cleaner'

a,b=3,4

while (b<=1000000):
    if b>= 100 and b<=1000000:
        print(b, end = ' ')
    a,b = b,a b

output:

123 199 322 521 843 1364 2207 3571 5778 9349 15127 24476 39603 64079 103682 167761 271443 439204 710647

What I want to do with it is, add a line break after every 5 numbers, so:

123 199 322 521 843
1364 2207 3571 5778 9349
...

and so forth.

I've done some googling and searching and I stumbled upon this (an example):

i = 1
while i < 30:
    print(i, end = '\n' if i % 5 == 0 else " ")
    i  = 1

but when i try to add it to my code:

while (b<=1000000):
    if b>= 100 and b<=1000000:
        print(b, end = '\n' if b % 5 == 0 else " ")
    a,b = b,a b

the output is still the same, all in one line:

123 199 322 521... 167761 271443 439204 710647

any ideas?

CodePudding user response:

You could maintain a counter and then print a newline after every 5 numbers:

a,b = 3,4
cnt = 1

while (b <= 1000000):
    if b >= 100 and b <= 1000000:
        print(b, end='')
        if cnt > 1 and cnt % 5 == 0:
            print('\n', end='')
        else:
            print(' ', end='')
        cnt  = 1
    a,b = b,a b

This prints:

123 199 322 521 843
1364 2207 3571 5778 9349
15127 24476 39603 64079 103682
167761 271443 439204 710647 

CodePudding user response:

In the code you found, i is both what is being printed & a count of what has been printed; you conflated the two.

i = 1
while (b<=1000000):
    if b>= 100 and b<=1000000:
        print(b, end = '\n' if i % 5 == 0 else " ")
        i  = 1
    a,b = b,a b
  • Related