Friday, September 16, 2022

[FIXED] Why does a for-loop create a new line while printing in Python?

Issue

I built a basic script that shows a string of random binary values (0 and 1) i times through a for loop.

It doesn't bother me, but in every loop, it automatically creates a new line and then prints the binary value

Example of the output:

1
0
1
1
0
...

Why is that? And how can I display the values in a "newlineless" string (without spaces too)?

Like 001010001011010111010, as an example.

Here's the code:


i = 20 #number of random binary to be shown

for x in range(i):
    bin = randint(0, 1)
    print(bin)

Solution

You need to specify the end parameter -- in this case, it's the empty string:

from random import randint

i = 20 #number of random binary to be shown
for x in range(i):
    val = randint(0, 1)
    print(val, end='', flush=True)

There are two other things worth noting:

  1. Don't use bin as a variable name -- it shadows a built-in.
  2. Standard output is buffered, which means that what you write to the console won't appear until a newline is written or the buffer is explicitly flushed. In this case, we pass flush=True so that our output appears on the console immediately.


Answered By - BrokenBenchmark
Answer Checked By - Clifford M. (PHPFixing Volunteer)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.