0

I tried running the following program:

for i in range(5): print(i, end=' ') 

However, it waits for me to write some string in the next line and gives the output like:

0 1 2 3 4 'Hi' 

where 'Hi' is what I input. I'm using the latest version 3.6.5 and can't seem to understand the reason behind this error. Can anyone help?

1 Answer 1

3

The default value for end is '\n', meaning that print() will write a newline character after printing the arguments. This would put the cursor on the next line.

Usually, stdout (to which print() writes by default) is also line buffered, meaning that data written to it is not flushed (and shown on your terminal) until a newline character is seen, to signal the end of the line.

You replaced the newline with a space, so no newline is written; instead a space is written, letting you write successive numbers one after the other on the same line.

Add an extra, empty print() call after your for loop to write the newline after looping:

for i in range(5): print(i, end=' ') print() 

You could also add flush=True to the print(..., end=' ') calls to explicitly flush the buffer.

Alternatively, for a small enough range(), pass in the values to print() as separate arguments, leaving end at the default. Separate arguments are separated by the sep argument, by default set to a space:

print(*range(5)) 

The * in front of the range() object tells Python to loop over the range() object and pass all values that produces as separate arguments to the print() call; so all 5 numbers are printed with spaces in between and a newline character at the end:

>>> print(*range(5)) 0 1 2 3 4 
Sign up to request clarification or add additional context in comments.

8 Comments

Thanks. This did the trick. However, I referred to this answer and still can't understand why that works and mine doesn't.I also tried a code to print characters in a string like mantra = "Always look on the bright side" and python still asks for a string prompt when I run the end = ' ' in print function.
Good answer, but I think the OP's question was asking why his code is waiting for an input rather than simply print 0 1 2 3 4 (although I couldn't reproduce it)
@A.B. Yas! That's exactly why I can't wrap my head around the fact that an empty print function makes the code work.
@KranKran: Right, updated my answer to explain why you don't see the line until there is a newline character. This is due to line buffering; the stdout file object holds on to data to minimise (slow) write operations. The idea is to collect multiple small writes into one big one, every time there is a newline character in the buffer.
I guess the follow-up question would be why those two lines of code, for OP, wait for an input, while when I try to run the same code, it instead prints and does not wait for an input
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.