0

In Python 2.7 (interactive mode), both:

print("Hey Joe")

and:

print "Hey Joe"

give output:

"Hey Joe"

What is the difference? When should I use the former and when the latter?

Thank you

glibdud
  • 7,550
  • 4
  • 27
  • 37
GabrieleMartini
  • 1,665
  • 2
  • 19
  • 26
  • 2
    `print "Hey Joe"` in python3 throws a syntax error. Are you on python2? – Primusa Jan 31 '19 at 21:30
  • 3
    There is no difference. A string with parens around it is still just a string. – RemcoGerlich Jan 31 '19 at 21:32
  • 2
    Use `from __future__ import print_function` and then it's just a function (to be used with parens) like in Python 3. But why on Earth are you still on 2? – RemcoGerlich Jan 31 '19 at 21:33
  • 2
    Python 3 was released in 2008, and the final end of life of 2 is january 1, 2020 -- eleven months from now. – RemcoGerlich Jan 31 '19 at 21:34
  • 1
    The one is called print statement and the other print function. Print function has been introduced with python 3 as print is really a function :) – Johnny Jan 31 '19 at 21:56

1 Answers1

-1

What is the difference?

Generally print 'something' is called print statement and print("something") is called print function. Print function has been introduced with Python 3. Other than that looking at the basic usage you won't notice any difference. However, you could find more here.

When should I use the former and when the latter?

If you want to make your code both Python 2.7 and Python 3 compliant than you should use print function, it is safe to import it with Python 2 and Python 3 it makes difference only with Python 2.

from __future__ import print_function
Johnny
  • 8,939
  • 2
  • 28
  • 33
  • 2
    On Python 2, unless you explicitly turn off the print statement with `from __future__ import print_function`, `print("something")` is still using the print statement. It's not the print function, as you can easily see when `print(1, 2)` prints a tuple and `print(1, file=whatever)` fails to parse. – user2357112 Jan 31 '19 at 22:09
  • You mean if you want to use print function on Python 2 always import it? – Johnny Jan 31 '19 at 22:12
  • 1
    Technically, it's a compiler directive that disables the print statement, not actually importing the print function - the print function is always there, but inaccessible because of the statement's existence. Still, yes, use `from __future__ import print_function`. – user2357112 Jan 31 '19 at 22:14
  • @user2357112 tnx for the explanation. I wasn't aware how its internally works. – Johnny Jan 31 '19 at 22:18