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