Python版本:3.1.2 IDE:IDLE (以下代碼都在該環境下實現)
新手需要注意的是Python 3.x和Python 2.x的區別。因爲Python是一門發展較快的語言,而現有的Python書籍大部分是介紹Python 2.x的,書上的某些程序在Python 3.x環境下可能運行出錯。如最簡單的HelloWorld程序:
>>> print "Hello World!"
SyntaxError: invalid syntax
#這是由於函數格式變化引起的,正確用法如下:
>>> print ("Hello World!")
Hello World!
再如獲取用戶輸入的程序:
>>> user = raw_input("Enter login name: ")
Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module>
user = raw_input("Enter login name: ")
NameError: name 'raw_input' is not defined
#這是由於函數名稱變化引起的,正確用法如下:
>>> user = input("Enter login name: ")
Enter login name: me
>>> user
'me'
可以通過文檔《What's New In Python 3.0》瞭解Python 3.x的具體變化。當書上的程序敲進去運行出錯的時候,可以通過help()找找問題出在什麼地方。如:
>>> help()
(介紹內容省略)
help> print
Help on built-in function print in module builtins:
print(...)
print(value, ..., sep=' ', end='/n', file=sys.stdout)
Prints the values to a stream, or to sys.stdout by default.
Optional keyword arguments:
file: a file-like object (stream); defaults to the current sys.stdout.
sep: string inserted between values, default a space.
end: string appended after the last value, default a newline.
PS:python入門書籍推薦