2012-09-19 54 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