'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
Solution 1:[1]
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 ", "))
...
Solution 2:[2]
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=", "
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 |
