Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
747 views
in Technique[技术] by (71.8m points)

printing - brackets around print in python

I have this line of code in python

print 'hello world'

against

print ('hello world')

can someone tell me the difference between the two?

I used it in a a simple code

var = 3
if var > 2: 
    print 'hello'

it fails for checking strictly for all values for var. But if I define the code as

var = 3
if var > 2: 
    print ('hello')

it works!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

For Python 2, it makes no difference. There, print is a statement and 'hello' and ('hello') are its argument. The latter gets simplified to just 'hello' and as such it’s identical.

In Python 3, the print statement was removed in favor of a print function. Functions are invoked using braces, so they are actually needed. In that case, the print 'hello' is a syntax error, while print('hello') invokes the function with 'hello' as its first argument.

You can backport the print function to Python 2, by importing it explicitly. To do that add the following as the first import of your module:

from __future__ import print_function

Then you will get the same behaviour from Python 3 in Python 2, and again the parentheses are required.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...