2012-09-19 51 views
1

我是Python的新手,我试图声明一个变量并打印它的值。python中的可变打印

这是我的代码:

#!C:\Python32\python.exe 
import sys 
import os 
import cgi 
import cgitb 
cgitb.enable() 
a = 5 
print(a)-------------------------> My doubt is in this line 

但是我的一个朋友写道行print a。在他的Python中,它正在打印该值,但在我的情况下,它显示为“无效语法”。这是为什么发生?

+2

读[最新消息在Python 3.0](http://docs.python.org/release/3.0.1/whatsnew/3.0.html#print-is-a-function) –

回答

4

由于您使用的是Python 3,print is a function,所以您将其称为:print(a)。在Python 2中(你的朋友正在使用什么),你可以忽略圆括号,并且将其称为:print a,但是这在以后不会工作,所以你的方法是正确的

此外,您的版本(print(a))将同时适用于Python 3和Python 2,因为只要它们匹配,额外的括号就会被忽略。我建议总是使用Python 3风格编写它,因为它在两者都有效。您可以更加明确,并通过使用(有些不可思议的)需要__future__ module

from __future__ import print_function 

print的功能会导致一些其他方面的差异,因为在Python 3,你可以设置一个变量指向print,或通过它作为参数的函数:

a = print 
a('magic') # prints 'magic' 

def add_and_call(func, num): 
    num += 1 
    func(num) 

add_and_call(print, 1) # prints 2 
+0

Thanks Brendan Long .. –

5

在Python 2,print不是一个函数,但关键字。因此括号不重要,print 'foo'print('foo')一起使用。

Python 3使print成为函数,其中具有被调用参数:print('foo')。将其称为print 'foo'将不再适用。

由于您在使用print作为关键字时出现错误,因此您使用的是Python 3.与您一样,您必须使用print作为函数。你的朋友正在使用Python 2,它可以同时工作。

的Python 3和Python 2类似,但也有,你应该了解,如果你在与别人谁使用不同版本的Python合作计划的几个主要差别:http://docs.python.org/py3k/whatsnew/3.0.html