'python doesn't print in same line with end = '' after number
I've made a program that makes a random change to a number every 10th of a second, and I want the new number to be printed in the same line as before. However, it just prints nothing when I add "end = '' " to the print command. Here's my code:
import random, time
stock = 1000000
while True:
change = random.randint(0, 10)
operation = random.randint(0, 1)
if operation == 0:
stock -= change
else:
stock += operation
print(stock, change, end = ' ')
time.sleep(0.1)
Solution 1:[1]
add flush=True and sep=' ' in your print function. That will make sure the print dynamically in one line. e.g
print(stock, change, sep=' ', end='', flush=True)
Solution 2:[2]
I'm guessing you would want to use
print(stock, change, end = '\r')
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 | Aadi |
| Solution 2 | paul-shuvo |
