简体   繁体   中英

Print dynamically in just one line

Been trying to improve my Fibonacci script. Made a few changes regarding actually how it visually looks (has like a minimalist "menu") and some other stuff to avoid it breaking, like not allowing text to be given as input to the amount of numbers it should generate. One of the things I wanted to change was the output to show all in just one line, but kinda been having a hard time doing so.

My code:

count = int(input("How many numbers do you want to generate?"))

a = 0
b = 0
c = 1
i = 0

while i < count:
    print(str(c))
    a = b
    b = c
    c = a + b
    i = i+1

What I also tried: Instead of print(str(c)) I've tried, without any luck:

    print("\033[K", str(c), "\r", )
    sys.stdout.flush()

Desired output:

1, 1, 2, 3 ,5

Output:

1
1
2
3
5

Use the end parameter of the print function, specifically in your example:

while i < count:
    print(c, end=", ")
    ...

To prevent the trailing comma after the last print:

while i < count:
    print(c, end=("" if i == count - 1 else ", "))
    ...

You can specifiy the ending of print :

print(*[1,2,3], end=", ")

The default ending is a new line

You can also specifiy a different separator with sep=", "

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