LPTHW - Day 04 A Good First Program

tl;dr : print is a statement in 2.x but in 3.x, print is a function.

As a developer with some experience with development, one will have the tendency of skipping the "hello, world" example. Nope, not going to happen here, I am going to do everything step by step. As Shunryu Suzuki once said,
"In the beginner's mind there are many possibilities, in the expert's mind there are few."
Being experienced and having an expert mentality make it harder to absorb new ways of doing stuff and unlearn all the bad habits. Do it like a beginner and no cut-and-paste.

Typed and ran the everything in below.

print "Hello World!"
print "Hello Again"
print "I like typing this"
print "This is fun."
print 'Yay! Printing.'
print "I'd much rather you 'not'."
print 'I "said" do not touch this.'

Works fine except when I ran it with Python3 and got this error message.
$ python3 ex1.py
File "ex1.py", line 1
print "Hello World!"
SyntaxError: invalid syntax

It seems to work in 2.6 but failed in 3 ? So what's going on here? According to the new features in Python3, print which used to be a statement in 2.x but now is a function in 3.x. Why ? According to Georg Brandl's rationale, as I read it, a function behaviours are easier to extend and overwrite compare to a statement.

So, change the Ex1 by adding a parenthesis around the strings we want to print as follows and save it as ex1-python3.py. Then you will get errorless output.

print("Hello World!")
print("Hello Again")
print("I like typing this")
print("This is fun.")
print('Yay! Printing.')
print("I'd much rather you 'not'.")
print('I "said" do not touch this.')

On a side note. There is no Day 3. Shits happens.

What if you want to stick to the Python 3 print function but still want to run it using version 2.x ? You can do this using future module which let's backport certain Python 3 features to Python 2. For our example for using print() function, we just need to import this function to our code as shown below. Thanks to kamal for this tip.
from __future__ import print_function

No comments:

Post a Comment