Python, standalone print meaning

Question:

I am confused as to what print alone does, let me explain:

if <something>:
     for i in x
          print "Hello"
     print

what is the point of the last print, does it do anything?

Asked By: FreshTendrils

||

Answers:

It prints new line in python 2.x. In python 3.x it would do nothing.

I suggest using python console to quickly check things like that.

Answered By: Dzarafata

It allows you to skip a new line in Python 2.

You can try by yourself by opening a Python interpretor:

>>> print

>>> 
Answered By: Maxime Chéramy

It prints a blank line. For example:

print 1
print 2
print
print 3

Gives:

1
2

3

Answered By: orlp

It prints a blank line. This is explained in the documentation:

A 'n' character is written at the end, unless the print statement ends with a comma. This is the only action if the statement contains just the keyword print.

It can be seeing by running your example:

if True:
     for i in [1,2,3,4]:
          print "Hello"
     print

Outputs:

> python test.py
Hello
Hello
Hello
Hello

>

Notice the blank line before the final prompt.

Answered By: Andy

Let’s use this block of code as an example:

print("Hello world 1")
print
print
print("Hello world 2")
print()
print()
print("Hello world 3")

In Python 3.x it does nothing because print() is a function. Output:

Hello world 1
Hello world 2


Hello world 3

In Python 2.x it prints a new line because print is a statement. Output:

Hello world 1


Hello world 2
()
()
Hello world 3

Source: https://docs.python.org/3/whatsnew/3.0.html

Answered By: bobasti
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.