Home > Net >  Why does a for-loop create a new line while printing in Python?
Why does a for-loop create a new line while printing in Python?

Time:04-16

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)

CodePudding user response:

print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)

it default end with a newline charater. if you want to have something else, you can do print('hi', end=something) where something is the string you want.
in you case something = ""

CodePudding user response:

In python, a line break is added by default every time you call print. If you instead would like to print something else you can customise this behaviour by changing end e.g. print(str, end=" ") would probably work for you.

CodePudding user response:

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.
  • Related