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?
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.
It allows you to skip a new line in Python 2.
You can try by yourself by opening a Python interpretor:
>>> print
>>>
It prints a blank line. For example:
print 1
print 2
print
print 3
Gives:
1
2
3
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.
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
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?
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.
It allows you to skip a new line in Python 2.
You can try by yourself by opening a Python interpretor:
>>> print
>>>
It prints a blank line. For example:
print 1
print 2
print
print 3
Gives:
1
23
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.
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