user6683787
user6683787

Reputation:

Why print command gives a new line even though there is no data to print

Just typing print only gives newline in python. Typing print without the brackets in 3.x will also gives a newline. Why?

Upvotes: 2

Views: 477

Answers (4)

cdarke
cdarke

Reputation: 44344

It is interesting how languages differ in this.

print in the Korn shell (ksh) has the same behaviour as python, i.e. it adds a newline. Bash does not have a print, relying on echo instead, which also adds a newline (which, like python, can be suppressed).

print in Perl does not, and caused so much inconvenience that another version, called say, was added which does add a newline.

Ruby and PHP are like Perl in that print also does not add a newline. This of course is less of an issue when embedded in HTML.

If you look at other languages, for example here you will find opinion divided as to whether a newline should be added or not. The removal of the newline in Python is discussed in PEP259.

Upvotes: 1

rkoots
rkoots

Reputation: 213

Because the default parameter in print is \n for the end, though if you pass parameter for print end variable as \t or space , then you can see the same !

But it works 2.7 and above!

Upvotes: 1

Harrison
Harrison

Reputation: 5376

In Python 3, print is now a function. It will print a new line character at the end of your statement.

If you don't specify an "end" it will by default use a new line character.

You can prevent this by doing something such as:

print("hello world", end="")

Upvotes: 1

Cory Kramer
Cory Kramer

Reputation: 117856

Because the documentation says so

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

Print objects to the text stream file, separated by sep and followed by end. sep, end and file, if present, must be given as keyword arguments.

All non-keyword arguments are converted to strings like str() does and written to the stream, separated by sep and followed by end. Both sep and end must be strings; they can also be None, which means to use the default values. If no objects are given, print() will just write end.

The file argument must be an object with a write(string) method; if it is not present or None, sys.stdout will be used. Since printed arguments are converted to text strings, print() cannot be used with binary mode file objects. For these, use file.write(...) instead.

Whether output is buffered is usually determined by file, but if the flush keyword argument is true, the stream is forcibly flushed.

Changed in version 3.3: Added the flush keyword argument.

Note that end is defaulted to '\n' which is a new line.

Upvotes: 6

Related Questions