In Python, which is more of a pythonian style of writing between these two:
1. print 'Hello'
or
2. print('Hello')

If u have a link on basic outlines of pythonian style and which syntax is a more pythonic way to use, it would be very useful to me. Thank You!

Recommended Answers

All 5 Replies

They are not Pythonic or unPythonic, but 1. is the way it used to be in Python 2 (it does not function in Python 3), second alternative is print as function, which is the style of Python 3 and Python 2 new versions if you do from __future__ import print_function.

But as 2. alternative has only one parameter, it works also in Python 2 even older versions of Python. So if you want to write code that directly works in Python 2, even Python 2.5, you can do printin with one parameter in paranthesis and use string formatting operation % and tuple of arguments for values. Then this works in any version of Python:

print('%i + %i = %i'% (2, 3, 2+3))

For recommended way to be Python 2 and Python 3 versions for bigger projects, it is recommended to write for Python 2 and do updates there. Then you can run the script through 2to3 script included in recent Python versions to produce another copy of script which only works in Python3.

Why you see here this second alternative of print use a lot here, is that it saves us contributors from detective work of figuring out which version the poster uses and that both Python 2 and Python 3 people reading the thread can try it out without changes.

Another thing to make both version compatible script needed is to define range to be xrange in Python 2 and input to be raw_input in Python 2. Disadvantage of this is that Python 2 user is using the style of Python 3, which can be little confusing.

try:
    range, input = xrange, raw_input
except:
    # Python 3 user does not need to do anything
    pass

Does first alternative not work in Python 3?

In most cases you can simply use the print() function, then it will work in both newer Python versions.
Print rightfully should be a function and not a statement, this was corrected in the newer versions.

Thank you all of you!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.