Should I use a print statement or function in Python 2.7?

To make my simple scripts in Python 2.7.10, should I use the print function instead of the instruction to make them future proof, in case I want to test them on another computer only with Python 3 or in the online IDE? What is the best way to work with both or the most common versions of Python?

What are the differences? This is my first programming language I'm learning, so I'm just not sure. Right now I have a fixed variable that I entered in either “2” or “3”, and then the if statement in the code performs another print function and concatenation method for both versions.

- Examples -

What i am using now:

print "Hello world!"

But should this be used in both versions?

print ("Hello world!")
+4
source share
4 answers

Python 2.7.10 has no function print()unless you import it. Adding brackets does not turn it into a function, it just indicates the grouping. If you try to simulate the transfer of multiple objects, it will print tuple.

>>> print 1
1
>>> print (1)
1
>>> print 1,2
1 2
>>> print (1,2)
(1, 2)

, print, Python 2 3, - , , . print (1,2) Python 3 , print 1,2 Python 2. , ( Python 2 3, Python 2):

>>> from __future__ import print_function
>>> print (1,2)
1 2
+10

Python 2 Python 3, __future__ import:

from __future__ import print_function

print() , Python 3.

, print, :

x = 100
print("Results:", x)

("Results:", 100) Python 2.x, Python 3.x, Results: 100, .

, , 2to3 print print().

unicode_literals, division .., Python 3. Python 3 .

+3

2.7, 3.x

print ("Hello world!")
print("Hello world!")

2.7 :

print "Hello world!"

, , PEP8 :

print("Hello world!")

.

, , :

from __future__ import print_function

python 2, , python 3. , , - :

print 1,2

.

print(1, 2)

python 2 , :

>>> print 1,2 
1 2
>>> print(1,2) 
(1, 2)
+1

Python 2, 3, print() , , ;

from __future__ import print_function

, Python 2, print .

>>> print ""
  File "<stdin>", line 1
    print ""
           ^
SyntaxError: invalid syntax

print(), :

>>> print(*[1,2,3,4], sep=':', end='!')
1:2:3:4!
+1

Source: https://habr.com/ru/post/1619286/


All Articles